Python中,使用文件作为stdin和stdout的子进程 [英] Python, Using files as stdin and stdout for subprocess
问题描述
具体来说,我怎么使用python子模块复制以下批处理命令:
Specifically, how do I replicate the following batch command using python subprocess module?:
myprogram<myinput.in > myoutput.out
如果你不知道,我想用myinput.in的内容作为标准输入和myoutput.out作为标准输出运行myprogram。
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是用C和I / O与scanf函数,printf的)
到目前为止,我已经试过如下:
(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()
和也,
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:
- 您打开
myoutput.out
只读 - 在打开的
myout中
但你用myoutput
- you open
myoutput.out
read only - it is opened as
myout
but then you usemyoutput
此外,壳= TRUE
是不必要在这里。
Also, shell=True
is unnecessary here.
下面应该工作:
myinput = open('myinput.in')
myoutput = open('myoutput.out', 'w')
p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput)
p.wait()
myoutput.flush()
这篇关于Python中,使用文件作为stdin和stdout的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!