python - 如何使用 python 与 exe 文件交互

标签 python input subprocess output exe

我有一个 exe 文件,它接受来自键盘的输入,并根据输入文本返回响应。当尝试读取 exe 返回的输出时,Python 脚本卡住。

我运行的是 Windows 7 和 python3.7。我已经尝试过continuously interacting with .exe file using python的答案.

from subprocess import Popen, PIPE

location = "C:\\Users\\file.exe"

p= Popen([location],stdin=PIPE,stdout=PIPE,stderr=PIPE, encoding="UTF8")
command='START'
p.stdin.write(command)
response=p.stdout.read()

我希望用输出文本填充响应,但程序却卡住在该行。

我想要交互的exe文件是here (胚胎文件)

最佳答案

调用p.stdout.readline()而不是p.stdout.read()。这将一次给您一行,而不是等待进程关闭其标准输出管道。欲了解更多信息,请阅读documentation .

这是一个更详细的示例。想象一下这个脚本是您的 exe 文件的替代品:

# scratch.py
from time import sleep

for i in range(10):
    print('This is line', i)
    sleep(1)

现在我启动该脚本,并尝试读取其输出:

from subprocess import Popen, PIPE, STDOUT

p = Popen(['python', 'scratch.py'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, encoding='UTF8')
for i in range(10):
    response = p.stdout.read()
    print('Response', i)
    print(response)

结果如下所示:它等待十秒钟,然后打印出以下内容:

Response 0
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9

Response 1

Response 2

Response 3

Response 4

Response 5

Response 6

Response 7

Response 8

Response 9

现在,如果我将其更改为 readline(),我会得到:

Response 0
This is line 0

Response 1
This is line 1

Response 2
This is line 2

Response 3
This is line 3

Response 4
This is line 4

Response 5
This is line 5

Response 6
This is line 6

Response 7
This is line 7

Response 8
This is line 8

Response 9
This is line 9

关于python - 如何使用 python 与 exe 文件交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56778748/

相关文章:

python - 类型错误: The added layer must be an instance of class Layer.在0x000001622999A5F8>处找到: <keras.layers.core.Dropout对象

python - 具有最大高度的 block 的组合

Python:无重复延迟的键盘输入

java - 从扫描仪获取字符输入

html - 如何在输入值中包含图像

python - 如何使用 Python 捕获 x265.exe 的实时命令行输出?

python - 未收到 Satchmo 下订单通知

python - 将未标记语料库转换为标记语料库 (NLTK)

python - 可选择将参数传递给 python 中的子进程

python - subprocess.Popen 尝试写入不存在的管道