Search code examples
pythonredirectstandardoutput

Python subprocess: how to retrieve the standard output


So, I'm writing a python script in which I need to call another python script that prints several lines in the standard output. I want to store the output of the callee script in a list, and process them in the main script.

One simple way is to print the result into a file (file3) and read the file, like this

subprocess.call("./vecdiff.py file1 file2 > file3")

f = open("file3", "r")

How can I redirect the output directly into some lists in my main script?


Solution

  • As below, redirect stdout and stderr of your child process to PIPE, then you can use 'communicate()' method to get the stdout and stderr of your child process from PIPE. The 'PIPE' is the pipe between father process and child process.

    from subprocess import Popen, PIPE
    p = Popen("./vecdiff.py file1 file2", stdout=PIPE, stderr=PIPE)
    output, errput = p.communicate()