Python threading.Timer()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16578652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:04:23  来源:igfitidea点击:

threading.Timer()

pythonpython-2.7

提问by sandra

i have to write a program in network course that is something like selective repeat but a need a timer. after search in google i found that threading.Timer can help me, i wrote a simple program just for test how threading.Timer work that was this:

我必须在网络课程中编写一个类似于选择性重复但需要计时器的程序。在谷歌搜索后,我发现 threading.Timer 可以帮助我,我写了一个简单的程序只是为了测试 threading.Timer 是如何工作的:

import threading

def hello():
    print "hello, world"

t = threading.Timer(10.0, hello)
t.start() 
print "Hi"
i=10
i=i+20
print i

this program run correctly. but when i try to define hello function in a way that give parameter like:

这个程序运行正确。但是当我尝试以提供如下参数的方式定义 hello 函数时:

import threading

def hello(s):
    print s

h="hello world"
t = threading.Timer(10.0, hello(h))
t.start() 
print "Hi"
i=10
i=i+20
print i

the out put is :

输出是:

hello world
Hi
30
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 726, in run
    self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

i cant understand what is the problem! can any one help me?

我不明白是什么问题!谁能帮我?

采纳答案by tom10

You just need to put the arguments to hellointo a separate item in the function call, like this,

您只需要将参数hello放入函数调用中的一个单独项目中,就像这样,

t = threading.Timer(10.0, hello, [h])

This is a common approach in Python. Otherwise, when you use Timer(10.0, hello(h)), the result of this function call is passed to Timer, which is Nonesince hellodoesn't make an explicit return.

这是 Python 中的常用方法。否则,当您使用 时Timer(10.0, hello(h)),此函数调用的结果将传递给Timer,这是None因为hello不会进行显式返回。