我正在使用通用的Python超时装饰器。我希望装饰器从它正在装饰的函数中访问变量。在此示例中,我希望消息从准备函数传递到超时函数。我不想使用全局变量,因为这听起来像是不好的做法。
def timeout(seconds):
def decorator(func):
def _handle_timeout(signum, frame):
# Do something with variable message
print("Sending the message didn't work!")
print(message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
@timeout(5)
def prepare(message):
"""Deploy app using Heroku to the MTurk Sandbox."""
print("Preparing to send message!")
send(message)
将处理程序推送到包装器中,以便它有权访问该变量。
from functools import wraps
import signal
import time
def timeout(seconds):
def decorator(func):
def wrapper(message, *args, **kwargs):
def _handle_timeout(signum, frame):
# Do something with variable message
print("Sending the message didn't work!")
print(message)
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(message, *args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
@timeout(1)
def prepare(message):
# Uncomment to force error
# time.sleep(3)
"""Deploy app using Heroku to the MTurk Sandbox."""
print("Preparing to send message!")
print(message)
if __name__ == "__main__":
prepare("hi")