30

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?

1 Answer 1

47

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()
Sign up to request clarification or add additional context in comments.

4 Comments

This looks close to what I need. How do I detect if errors occurred?
Nevermind. stderr=subprocess.PIPE, then, if stderr: print error
In the line myoutput = open('myoutput.out'. 'w') parameters should be separated by a ,, not a .
While this answer remains correct, note that subprocess.run(), added in Python 3.5, is a nicer API for the majority of subprocess use cases. It similarly takes stdin and stdout keyword arguments.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.