我正在尝试实现需要运行外部可执行文件的 python 代码。经过一些研究,我找到了 subprocess
模块并尝试了它。但是,当我运行代码时,子进程退出并返回一个 CompletedProcess
对象,这对我来说不合适,因为我正在使用的 .exe 实际上是一个 continuous 程序它接受输入并生成输出直到关闭。 (我的程序将发送输入并接收输出。)
所以这段代码失败了。
import subprocess
proc = subprocess.run("some.exe", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(proc) # To see what it is.
它捕获程序首先在 stdout 中输出然后退出,而不是期待新的输入。
我在这里的术语也有问题,我正在使用的这个可执行文件能够运行命令,同时仍然能够接收新命令,这称为异步还是非-阻塞 ?
关于我的问题,正确的处理方式是什么?有很多问题非常接近这个,但我无法确定哪些是在回答我的问题或以现代方式回答它(有非常古老的问题)。
看起来 subprocess
模块在 Python 3.6.1 中发生了一些变化 https://docs.python.org/3/library/subprocess.html
所以最好能提供最新的解决方案,或者至少说说更新的方式和运作方式。
我正在使用 Windows 10、Python 3.6.1
Edit1:我遇到过 subprocess.Popen
,这可能是我需要的,但我还没有发现如何正确使用它。
Edit2: 模块 pexpect
似乎是为这类问题设计的,但我不确定使用它是否会让我的时间更轻松。任何建议表示赞赏。
最佳答案
来自文档:
subprocess.run()
Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.
由于您的子进程在初始调用后并未结束,因此您不能使用 run
,而是需要使用 Popen
。
你可以使用这样的东西:
import subprocess
p = subprocess.Popen(exe_path,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while p.poll() is None:
p.stdin.write(some_command)
p.stdin.flush()
out = p.stdout.readline()
但请注意,这可能会导致死锁,如 documentation 中所述。 :
Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
不幸的是,您不能使用communicate
,因为这会要求您使用所有输入来调用流程。我会尝试使用上面的版本,看看缓冲区是否真的会导致您的应用程序出现问题。
关于python - 使用 Python 运行连续的 .exe 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43432484/