I need to run a shell command from python and store the output in a string or file -


this question has answer here:

i use ls example:

i tried:

str = call("ls") 

str stored 0.

i tried:

str = call("ls>>txt.txt") 

but had no luck (an error occured & txt.txt wasn't created).

how perform straight-forward task.

[i had imported call]

edit: call runs command in shell, returns return value of command. since ls successful, call('ls') returned 0.

if trying run ls, suggest using glob:

from glob import glob file_list = glob('*') 

if want more complicated, suggestion use subprocess.popen() this:

from subprocess import popen, pipe  ls_proc = popen('ls', stdout=pipe, stderr=pipe) out, err = ls_proc.communicate() 

note, in stdout , stderr keywords, pipe can replaced file-like object, can send output file if want. also, should read popen.communicate() prior using since if command call hangs, python routine hang.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -