Using files as stdin and stdout for subprocess

Nolander picture Nolander · Mar 1, 2013 · Viewed 25.8k times · Source

How do I replicate the following batch command using python subprocess module?

myprogram < myinput.in > myoutput.out

In other words, how do I run myprogram using the contents of myinput.in as the standard input and myoutput.out as standard output?

Answer

Elmar Peise picture Elmar Peise · Apr 9, 2013

The following should work:

myinput = open('myinput.in')
myoutput = open('myoutput.out', 'w')
p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput)
p.wait()
myoutput.flush()