RecursionError: maximum recursion depth exceeded while using thread

RecursionError: maximum recursion depth exceeded while using thread

所以我得到了错误

[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

我运行的密码是

import threading

def hello_world(a):
    threading.Timer(2.0, hello_world(a)).start() # called every minute
    print(a)
    print("Hello, World!")

hello_world('a')

我注意到当 hello_world 函数中没有参数时,不会发生错误。但是只要我需要将参数传递给函数,我就会收到错误消息。有人可以解释为什么会这样以及如何解决它吗?

The threading.Timer() constructor expects the function and the arguments to pass to that function as separate parameters。正确的调用方式是这样的:

threading.Timer(2.0, hello_world, (a,)).start()

可以看到我们引用了hello_world没有调用,我们把要传的参数单独列在一个1元组(a,).

目前这样做的方式是,它会在到达表达式末尾之前立即评估hello_world(a),试图找出return hello_world(a) 的值将是 - 而不是启动计时器,然后在每次计时器关闭时计算表达式。