使用 Python 子进程模块将输入传递给可执行文件 [英] Passing input to an executable using Python subprocess module
问题描述
我有一个名为 0.in
的输入文件.为了得到输出我做 ./a.out <0.in
在 Bash Shell 中.
I have an input file called 0.in
. To get the output I do ./a.out < 0.in
in the Bash Shell.
现在,我有几个这样的文件(超过 500 个),我想使用 Python 的 subprocess 模块自动化这个过程.
Now, I have several such files (more than 500) and I want to automate this process using Python's subprocess module.
我试过这样做:
data=subprocess.Popen(['./a.out','< 0.in'],stdout=subprocess.PIPE,stdin=subprocess.PIPE).communicate()
当我运行此程序时,没有打印任何内容(数据 [0] 为空白).做我想做的事的正确方法是什么?
Nothing was printed (data[0] was blank) when I ran this. What is the right method to do what I want to do?
推荐答案
使用 <
进行重定向是 shell 功能,而不是 python 功能.
Redirection using <
is a shell feature, not a python feature.
有两种选择:
使用
shell=True
并让 shell 处理重定向:
Use
shell=True
and let the shell handle redirection:
data = subprocess.Popen(['./a.out < 0.in'], stdout=subprocess.PIPE, shell=True).communicate()
让python处理重定向:
Let python handle redirection:
with open('0.in') as f:
data = subprocess.Popen(['./a.out'], stdout=subprocess.PIPE, stdin=f).communicate()
第二个选项通常是首选,因为它避免了 shell 的变幻莫测.
The second option is usually preferred because it avoids the vagaries of the shell.
如果要在data
中捕获stderr,则将stderr=subprocess.PIPE
添加到Popen
命令中.否则,stderr 将出现在终端或发送 python 错误消息的任何地方.
If you want to capture stderr in data
, then add stderr=subprocess.PIPE
to the Popen
command. Otherwise, stderr will appear on the terminal or wherever python's error messages are being sent.
这篇关于使用 Python 子进程模块将输入传递给可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!