【发布时间】:2022-01-26 07:07:35
【问题描述】:
我有一个名为 my_program 的程序来操作系统。该程序在 Linux 上运行,我正在尝试使用 Python 将其自动化。 my_program 不断生成输出,并假设接收输入并对其做出响应。 当我在 bash 中运行 my_program 时,它确实可以正常工作,我从程序接收到恒定输出,当我按下某个序列(例如 /3 更改系统模式)时,程序以输出响应.
开始我正在使用的过程:
self.process = Popen(my_program,stdin=PIPE,stdout=PIPE,text=True)
为了将输入写入我正在使用的系统:
self.process.stdin.write('/3')
但是写的好像不行,我也试过用:
self.process.communicate('/3)
但由于我的系统不断生成输出,它使进程死机并且整个程序卡住了。
对于写入不断生成输出的进程的任何解决方案?
编辑: 我认为我无法提供可以重现该问题的代码,因为我使用的是我公司拥有的独特软件,但它是这样的:
self.process = Popen(my_program,stdin=PIPE,stdout=PIPE,text=True)
self.process.stdin.write('/3')
# try to find a specific string that indicated that the input string was received
string_received = False
while(string_received = False):
response = self.process.stdout.readline().strip()
if (response == expected_string):
break
【问题讨论】:
-
@pynexj 我编辑了我的问题以包含更清晰的内容,tnx
-
“似乎不起作用”——这是一种解释,但缺少可观察到的事实。请创建一个minimal reproducible example 并展示您所看到的内容。
-
在刷新缓冲区之前,只写几个字节不会做任何事情。您可以在创建子进程时设置最小缓冲区或关闭缓冲。
-
@tripleee 你能详细说明一下吗?