在子过程中设置超时并捕获实时stdout
我正在通过子过程运行外部脚本。该脚本生成了自己的日志,我需要在Python脚本中打印。这是我现在正在做的事情:
proc = subprocess.Popen(external_script, \
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
logger.info(f"{line}")
现在,这个外部脚本需要一段时间才能完成,因此我也想为此设置超时。但是,Popen构造函数不需要超时参数。我可以将popen.communate()与超时使用,但是我不知道如何使用communicate()读取ligs live。我相信communicate()等待该过程完成/超时到期,然后允许您阅读Stdout。
有没有办法两者: a)设置超时 b)从子过程中阅读现场演出?
I am running an external script via subprocess. This script generates its own logs which I need to print within my Python script. Here's how I'm doing it right now:
proc = subprocess.Popen(external_script, \
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
logger.info(f"{line}")
Now, this external script takes a while to complete, so I also want to set a timeout for it. However, the Popen constructor does not take a timeout argument. I could use Popen.communicate() with a timeout, but I do not know how to read the logs live using communicate(). I believe communicate() waits till the process is complete/timeout expires and then allows you to read stdout.
Is there a way to both:
a) set a timeout AND
b) read live stdout from the subprocess ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,但不是直接使用Popen。使用线程中的计时器类
Yes there is, but not directly using Popen. Use Timer class from threading