Subprocess.Popen () IO Forwarding

Attempt to redirect subprocess output to a file.

server.py:

while 1: print "Count " + str(count) sys.stdout.flush() count = count + 1 time.sleep(1) 

Laucher:

 cmd = './server.py >temp.txt' args = shlex.split(cmd) server = subprocess.Popen( args ) 

The output is displayed on the screen, temp.txt remains empty. What am I doing wrong?

As a background, I am trying to capture the output of a program that is already written.

I can not use:

 server = subprocess.Popen( [exe_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE) 

since the program may not be hidden. Instead, I was going to redirect the output through fifo. This works fine if I manually start server.py, but obviously not, if I Popen() calls the redirect, it doesn't work. ps -aux indicates that server.py was started correctly.

+8
python popen
source share
2 answers

Enjoying, you can use the stdout parameter with the file:

 with open('temp.txt', 'w') as output: server = subprocess.Popen('./server.py', stdout=output) server.communicate() 

As explained in the documentation :

stdin, stdout and stderr specify standard input for executable programs, standard output, and standard error file files, respectively. Valid values ​​are PIPE, an existing file descriptor (positive integer), an existing file object, and None.

+7
source share

Redirecting output with ">" is a wrapper function - by default, subprocess.Popen does not instantiate. This should work:

 server = subprocess.Popen(args, shell=True) 
+4
source share

All Articles