darksky
darksky

Reputation: 21019

Printing to stdout in subprocess

I have a script which runs a subprocess as follows:

child_process = subprocess.Popen(["python", testset['dir'] + testname, \                                                                                                                                     
                              output_spec_file, plugin_directory],\                                                          
                              stderr=subprocess.PIPE, stdout=subprocess.PIPE)

In that process, I am trying to insert print statements but they are not appearing to stdout. I tried using sys.stdout.write() in that subprocess and then sys.stduout.read() right after child_process but it is not capturing the output.

I am new to Python and I haven't gotten to that level of complexity in Python. I am actually working low level in C and there are some Python test scripts and I'm not sure how to print out from the subprocess.

Any suggestions?

Upvotes: 0

Views: 401

Answers (1)

mgilson
mgilson

Reputation: 309881

sys.stdout.read (and write) are for standard input/output of the current process (not the subprocess). If you want to write to stdin of the child process, you need to use:

child_process.stdin.write("this goes to child")  #Popen(..., stdin=subprocess.PIPE)

and similar for reading from the child's stdout stream:

child_process = subprocess.Popen( ... , stdout=subprocess.PIPE)
child_process.stdout.read("This is the data that comes back")

Of course, it is generally more idiomatic to use:

stdoutdata, stderrdata = child_process.communicate(stdindata)

(taking care to pass subprocess.PIPE to the Popen constructor where appropriate) provided that your input data can be passed all at once.

Upvotes: 1

Related Questions