首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python -运行进程并等待输出

Python -运行进程并等待输出
EN

Stack Overflow用户
提问于 2018-06-09 07:14:09
回答 2查看 2.4K关注 0票数 4

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

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

程序输出在stdout和日志文件中,两者都可以使用。

使用linux。

到目前为止的代码:

代码语言:javascript
复制
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脚本变得更慢。此外,这也是一个愚蠢的解决方案。

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2018-06-09 09:09:07

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

票数 0
EN

Stack Overflow用户

发布于 2018-06-09 07:43:32

您可以使用命令而不是子进程。下面是一个使用ls命令的示例:

代码语言:javascript
复制
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)
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50769466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档