Using files as stdin and stdout for subprocess
29,549
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()
Related videos on Youtube
Author by
Nolander
Updated on February 20, 2020Comments
-
Nolander about 4 years
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 ofmyinput.in
as the standard input andmyoutput.out
as standard output? -
Doo Dah over 10 yearsThis looks close to what I need. How do I detect if errors occurred?
-
Doo Dah over 10 yearsNevermind. stderr=subprocess.PIPE, then, if stderr: print error
-
flagg19 over 9 yearsIn the line
myoutput = open('myoutput.out'. 'w')
parameters should be separated by a,
, not a.
-
Mark Amery about 7 yearsWhile this answer remains correct, note that
subprocess.run()
, added in Python 3.5, is a nicer API for the majority ofsubprocess
use cases. It similarly takesstdin
andstdout
keyword arguments.