我想运行一个程序,等待它的输出,向它发送输入,然后重复执行,直到出现一个条件。
我找到的所有问题都是关于等待程序完成的问题,但事实并非如此。进程仍将运行,只是不会给出任何(新的)输出。
程序输出在stdout和日志文件中,两者都可以使用。
使用linux。
到目前为止的代码:
import subprocess
flag = True
vsim = subprocess.popen(['./run_vsim'],
stdin=subprocess.pipe,
shell=true,
cwd='path/to/program')
while flag:
with open(log_file), 'r') as f:
for l in f:
if condition:
break
vsim.stdin.write(b'do something\n')
vsim.stdin.flush()
vsim.stdin.write(b'do something else\n')
vsim.stdin.flush()
现在,甚至在程序启动完成之前,“做点什么”输入就会被多次发送。此外,在程序完成从最后一个while iteraction开始运行命令之前,将读取日志文件。这会导致它缓冲输入,所以即使在满足条件后,我也会继续执行命令。
我可以在每个stdin.write
之后使用time.sleep
,但由于执行每个命令所需的时间是可变的,因此我需要使用比必要时间更长的时间,从而使python脚本变得更慢。此外,这也是一个愚蠢的解决方案。
谢谢!
发布于 2018-06-09 09:09:07
如果您使用的是python3,您可以尝试更新代码以使用subprocess.run
。它应该等待您的任务完成并返回输出。
发布于 2018-06-09 07:43:32
您可以使用命令而不是子进程。下面是一个使用ls命令的示例:
import commands
status_output = commands.getstatusoutput('ls ./')
print status_output[0] #this will print the return code (0 if everything is fine)
print status_output[1] #this will print the output (list the content of the current directory)
https://stackoverflow.com/questions/50769466
复制相似问题