Python-运行进程并等待输出

dra*_*amm 5 python subprocess python-3.x

我想运行一个程序,等待它的输出,向它发送输入并重复直到出现条件。

我所能找到的只是有关等待程序完成的问题,但事实并非如此。该进程仍将运行,只是不会提供任何(新的)输出。

程序输出位于标准输出和日志文件中,两者都可以使用。
使用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()
Run Code Online (Sandbox Code Playgroud)

事实上,即使在程序完成启动之前,“做某事”输入也会被发送多次。此外,在程序完成运行最后一次 while 迭代中的命令之前,会读取日志文件。这会导致它缓冲输入,因此即使在满足条件后我也会继续执行命令。

time.sleep我可以在每个命令之后使用stdin.write,但由于执行每个命令所需的时间是可变的,我需要使用比必要的时间更长的时间,从而使 python 脚本变慢。另外,这是一个愚蠢的解决方案。

谢谢!

Wal*_*Da. -2

您可以使用命令而不是子进程。这是 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)
Run Code Online (Sandbox Code Playgroud)