pythonshellsubprocess

How do I pipe a subprocess call to a text file?


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

RIght now I have a script that I run. When I run it and it hits this line, it starts printing stuff because run.sh has prints in it.

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


Solution

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

    It takes either

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

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

    I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

    As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.