How to transfer a subprocess call to a text file?

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"]) 

Now I have a script that I am running. When I run it and it falls into this line, it starts to print the material because run.sh has prints in it.

How do I transfer this to a text file? (And also print if possible)

+50
python linux unix shell subprocess
Jan 31 2018-11-21T00:
source share
2 answers

If you want to write the output to a file, you can use the stdout argument subprocess.call .

Requires None , subprocess.PIPE , a file object, or a file descriptor. The first is default: stdout is inherited from the parent (your script). The second allows you to move from one team / process to another. The third and fourth is that you want the result to be written to a file.

You need to open the file with something like open and pass the integer of the object or file descriptor to call :

 f = open("blah.txt", "w") subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=f) 

I assume that any valid file object will work like a socket (gasp :)), but I never tried.

As marcog is mentioned in the comments, which you might want to redirect to stderr, you can redirect it to the same place as stdout with stderr=subprocess.STDOUT . Any of the above values ​​work as well, you can redirect to different places.

+87
Jan 31 '11 at 10:04
source share

popen parameters can be used in call

 args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0 

So...

 subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=myoutput) 

Then you can do what you want with myoutput (which should be a btw file).

Alternatively, you can do something closer to an output channel like this.

 dmesg | grep hda 

:

 p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] 

There is a lot of great useful info on the python manual page .

+16
Jan 31 '11 at 10:01
source share



All Articles