Specifically, how do I replicate the following batch command using python subprocess module?:
myprogram myoutput.out
If you don't know, I am trying to run myprogram using the contents of myinput.in as the standard input and myoutput.out as standard output.
(myprogram is written in c and I/O with scanf, printf)
So far I have tried the following:
myinput = open('myinput.in')
myout = open('myoutput.out')
p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput, shell=True)
p.wait()
myoutput.flush()
And also,
myinput = open('myinput.in')
myout = open('myoutput.out')
inputs = myinput.read()
myinput.close()
myprogram = subprocess.Popen('myprogram.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True)
outputs = myprogram.communicate(input=inputs)[0]
myout.write(str(outputs))
myout.close()
Neither one of these writes anything to output, however when I run my batch command, it works like a charm. :/ Please tell me I'm missing something obvious.
解决方案
The error messages from python should tell you exactly what is going wrong:
you open myoutput.out read only
it is opened as myout but then you use myoutput
Also, shell=True is unnecessary here.
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()