以指定的最大运行时间运行外部程序

发布于 2024-09-04 01:47:51 字数 139 浏览 3 评论 0原文

我想在多线程Python程序的每个线程中执行外部程序。

假设最大运行时间设置为 1 秒。如果启动的进程在 1 秒内完成,主程序将捕获其输出以进行进一步处理。如果它没有在 1 秒内完成,主程序就会终止它并启动另一个新进程。

如何实施?

I want to execute an external program in each thread of a multi-threaded python program.

Let's say max running time is set to 1 second. If started process completes within 1 second, main program capture its output for further processing. If it doesn't finishes in 1 second, main program just terminate it and start another new process.

How to implement this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

蓝眼睛不忧郁 2024-09-11 01:47:51

您可以定期轮询它:

import subprocess, time

s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
    time.sleep(poll_period)
    timeout -= poll_period
    s.poll()
if timeout <= 0:
    s.kill() # timed out
else:
    pass # completed

然后您可以将上述内容放入函数中并将其作为线程启动。

You could poll it periodically:

import subprocess, time

s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
    time.sleep(poll_period)
    timeout -= poll_period
    s.poll()
if timeout <= 0:
    s.kill() # timed out
else:
    pass # completed

You can then just put the above in a function and start it as a thread.

甜是你 2024-09-11 01:47:51

这是我使用的辅助函数:

def run_with_timeout(command, timeout):
    import time
    import subprocess

    p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while timeout > 0:
        if p.poll() is not None:
            return p.communicate()
        time.sleep(0.1)
        timeout -= 0.1
    else:
        try:
            p.kill()
        except OSError as e:
            if e.errno != 3:
                raise
    return (None, None)

This is the helper function I use:

def run_with_timeout(command, timeout):
    import time
    import subprocess

    p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while timeout > 0:
        if p.poll() is not None:
            return p.communicate()
        time.sleep(0.1)
        timeout -= 0.1
    else:
        try:
            p.kill()
        except OSError as e:
            if e.errno != 3:
                raise
    return (None, None)
拥抱我好吗 2024-09-11 01:47:51

Linux 上的一个令人讨厌的黑客行为是使用timeout程序来运行命令。不过,您可以选择更好的全 Python 解决方案。

A nasty hack on linux is to use the timeout program to run the command. You may opt for a nicer all Python solution, however.

鹿港小镇 2024-09-11 01:47:51

这是使用 pexpect 模块的解决方案(我需要在程序超时之前捕获程序的输出,我没有设法使用 subprocess.Popen 来做到这一点):

import pexpect

timeout = ... # timeout in seconds

proc = pexpect.spawn('foo', ['args'], timeout = timeout)

result = proc.expect([ pexpect.EOF, pexpect.TIMEOUT])

if result == 0:
  # program terminated by itself
  ...
else:
  # result is 1 here, we ran into the timeout
  ...

print "program's output:", print proc.before

here is a solution using the pexpect module (I needed to capture the output of the program before it ran into the timeout, I did not manage to do this with subprocess.Popen):

import pexpect

timeout = ... # timeout in seconds

proc = pexpect.spawn('foo', ['args'], timeout = timeout)

result = proc.expect([ pexpect.EOF, pexpect.TIMEOUT])

if result == 0:
  # program terminated by itself
  ...
else:
  # result is 1 here, we ran into the timeout
  ...

print "program's output:", print proc.before
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文