Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91087 > unrolled thread
| Started by | Jason Friedman <jsf80238@gmail.com> |
|---|---|
| First post | 2015-05-22 20:15 -0600 |
| Last post | 2015-05-22 20:15 -0600 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
decorators and alarms Jason Friedman <jsf80238@gmail.com> - 2015-05-22 20:15 -0600
| From | Jason Friedman <jsf80238@gmail.com> |
|---|---|
| Date | 2015-05-22 20:15 -0600 |
| Subject | decorators and alarms |
| Message-ID | <mailman.249.1432347717.17265.python-list@python.org> |
I have the following code to run a shell command and kill it if it
does not return within a certain amount of time:
def run_with_time_limit(command, limit):
"""Run the given command via a shell.
Kill the command, and raise an exception, if the
execution time exceeds <limit> seconds.
Else return (exit_code, stdout, stderr, duration)."""
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
start_stamp = time.time()
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(limit)
try:
process = subprocess.Popen(
command,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True)
stdout, stderr = process.communicate()
duration = time.time() - start_stamp
signal.alarm(0) # reset the alarm
except Alarm:
process.kill()
raise Alarm("The command did not return within %(limit)s
seconds." % locals())
return (process.returncode, stdout, stderr, duration)
run_with_time_limit("sleep 2", 1)
This works as desired.
But, I'd like to expand this to take some generic code, not just a
shell command, and terminate it if it does not return quickly.
@time_limiter
def generic_function(arg1, arg2, time_limit=10):
do_some_stuff()
do_some_other_stuff()
return val1, val2
If generic_function does not finish within 10 seconds it would stop
executing and throw an exception.
May I have some hints, please?
Back to top | Article view | comp.lang.python
csiph-web