在子过程中设置超时并捕获实时stdout

发布于 2025-02-09 23:15:22 字数 447 浏览 1 评论 0原文

我正在通过子过程运行外部脚本。该脚本生成了自己的日志,我需要在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌能量女王 2025-02-16 23:15:22

是的,但不是直接使用Popen。使用线程中的计时器类

from threading import Timer
proc = subprocess.Popen(external_script, \
           stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Timer(TIMEOUT,proc.terminate).start() # call proc.terminate() from another thread after TIMEOUT seconds

for line in proc.stdout:
    logger.info(f"{line}")

Yes there is, but not directly using Popen. Use Timer class from threading

from threading import Timer
proc = subprocess.Popen(external_script, \
           stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Timer(TIMEOUT,proc.terminate).start() # call proc.terminate() from another thread after TIMEOUT seconds

for line in proc.stdout:
    logger.info(f"{line}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文