How to limit program's execution time when using subprocess?

独自空忆成欢 提交于 2019-12-04 04:54:12

do it like so in your command line:

perl -e 'alarm shift @ARGV; exec @ARGV' <timeout> <your_command>

this will run the command <your_command> and terminate it in <timeout> second.

a dummy example :

# set time out to 5, so that the command will be killed after 5 second 
command = ['perl', '-e', "'alarm shift @ARGV; exec @ARGV'", "5"]

command += ["ping", "www.google.com"]

exec_proc = subprocess.Popen(command)

or you can use the signal.alarm() if you want it with python but it's the same.

If you're using Python 2.6 or later, you can use the multiprocessing module.

from multiprocessing import Process

def f():
    # Stuff to run your process here

p = Process(target=f)
p.start()
p.join(timeout)
if p.is_alive():
    p.terminate()

Actually, multiprocessing is the wrong module for this task since it is just a way to control how long a thread runs. You have no control over any children the thread may run. As singularity suggests, using signal.alarm is the normal approach.

import signal
import subprocess

def handle_alarm(signum, frame):
    # If the alarm is triggered, we're still in the exec_proc.communicate()
    # call, so use exec_proc.kill() to end the process.
    frame.f_locals['self'].kill()

max_time = ...
stdout = stderr = None
signal.signal(signal.SIGALRM, handle_alarm)
exec_proc = subprocess.Popen(['time', 'ping', '-c', '5', 'google.com'],
                             stdin=None, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
signal.alarm(max_time)
try:
    (stdout, stderr) = exec_proc.communicate()
except IOError:
    # process was killed due to exceeding the alarm
finally:
    signal.alarm(0)
# do stuff with stdout/stderr if they're not None
Woooee

I use os.kill() but am not sure if it works on all OSes.
Pseudo code follows, and see Doug Hellman's page.

proc = subprocess.Popen(['google-chrome'])                                               
os.kill(proc.pid, signal.SIGUSR1)</code>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!