python - 如何让装饰器从被装饰函数访问变量?

标签 python timeout signals decorator python-decorators

我正在使用通用的 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")

关于python - 如何让装饰器从被装饰函数访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46689923/

相关文章:

python - 如何从源代码重建 python youtube-dl

python - 如何填充 numpy 数组的 "partial diagonal axis"

android - 连接超时时数据是否已经发送到服务器

c - 如果已经设置了警报, alarm() 的返回值是多少

c - x86, amd64 : Why SIGTRAP' ucontext instruction pointer does not point to related int3

c++ - 为什么 "find usage"不适用于不同子项目中的信号

python pandas,某些列到行

python - ImproperlyConfigured : SQLite 3. 需要 8.3 或更高版本(发现 3.7.17)

java - 如何强制 DriverManager.getConnection() 方法调用超时?

ios - AFNetworking 超时