[英]threading.Timer()
我必須在網絡課程中編寫一個類似於選擇性重復但需要計時器的程序。 在谷歌搜索后,我發現 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
這個程序運行正確。 但是當我嘗試以提供如下參數的方式定義 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
輸出是:
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
我不明白是什么問題! 誰能幫我?
你只需要把hello
的參數放到函數調用中的一個單獨的項目中,就像這樣,
t = threading.Timer(10.0, hello, [h])
這是 Python 中的常用方法。 否則,當您使用Timer(10.0, hello(h))
,此函數調用的結果將傳遞給Timer
,因為hello
沒有顯式返回,所以它是None
。
如果您想使用普通函數參數,另一種方法是使用lambda
。 基本上它告訴程序參數是一個函數,不能在賦值時調用。
t = threading.Timer(10.0, lambda: hello(h))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.