我遵循this解决方案。
我正在尝试为我的函数during runtime
设置超时秒数,这使我可以灵活地传递不同的timeout seconds
,甚至无需打开脚本。(test.py)
timeout.py
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=60, error_message=(os.strerror(errno.ETIMEDOUT)).upper()):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
#print "Timeout seconds =: " , seconds
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
main.py(只接受运行时传递的任何参数)
import test
if __name__ == '__main__':
args1=sys.argv[1]
args2=sys.argv[2]
time_sec = sys.argv[3]
test.func(args1,arg2,time_sec)
test.py
from timeout import timeout
from timeout import TimeoutError
#@timeout(30)
@timeout() #<--here i want to pass timeout_sec
def func(args1,args2,timeout_sec):
#do something
运行此:
python main.py abc abc 45 #this overrids seconds from timeout.py
在test.py中timeout()
或timeout(30)
会起作用,但有没有办法让它变得动态,并将秒数传递为&#34; arg3&#34;在@timeout(arg3)
有什么方法可以达到这个目的吗?