Skip to content Skip to sidebar Skip to footer

Subprocess.Popen() IO Redirect

Trying to redirect a subprocess' output to a file. server.py: while 1: print 'Count ' + str(count) sys.stdout.flush() count = count + 1 time.sleep(1) Laucher: cmd

Solution 1:

Altenatively, you can use the stdout parameter with a file object:

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 the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.


Solution 2:

Output redirection with ">" is a feature of shells - by default, subprocess.Popen doesn't instantiate one. This should work:

server = subprocess.Popen(args, shell=True)

Post a Comment for "Subprocess.Popen() IO Redirect"