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()
Share:
29,549

Related videos on Youtube

Nolander
Author by

Nolander

Updated on February 20, 2020

Comments

  • Nolander
    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 of myinput.in as the standard input and myoutput.out as standard output?

  • Doo Dah
    Doo Dah over 10 years
    This looks close to what I need. How do I detect if errors occurred?
  • Doo Dah
    Doo Dah over 10 years
    Nevermind. stderr=subprocess.PIPE, then, if stderr: print error
  • flagg19
    flagg19 over 9 years
    In the line myoutput = open('myoutput.out'. 'w') parameters should be separated by a ,, not a .
  • Mark Amery
    Mark Amery about 7 years
    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.