Python - 运行进程并等待输出

标签 python python-3.x subprocess

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

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

程序输出在标准输出和日志文件中,两者都可以使用。
使用 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 迭代的命令之前读取日志文件。这导致它缓冲输入,所以即使在满足条件后我也会继续执行命令。

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

谢谢!

最佳答案

如果您使用的是 python3,则可以尝试更新您的代码以改用 subprocess.run。它应该等待您的任务完成并返回输出。

关于Python - 运行进程并等待输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50769466/

相关文章:

python - python类中的声明等同于_init_?

python - 无法使用 api 将数据上传到 thingworx

python - 返回要索引的文本文件中的项目列表

python - 在Python中使用循环和数组更改条件

python - 将 subprocess.Popen 输出附加到文件?

Python Pandas 绘制标题名称传递字符串

python - pandas 中删除的列重新出现

python - 正则表达式 findall 匹配字符串中的字母 "a"到 "z"后跟另一个字符

python - 避免用户中止 python 子进程

python - 在 Python 3.2 中调用 Python 2.7 模块