2013-05-16 8 views
19

私は選択コースのようなものですが、タイマーが必要なプログラムをネットワークコースで書く必要があります。グーグルで検索した後、私は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 

を。 しかし、ときに私は次のようにパラメータを与える方法で、ハロー関数を定義しよう:

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 

私は問題が何であるかを理解するカント!誰でも助けてくれますか?

答えて

47

は、あなただけの

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

これは、Pythonでの一般的なアプローチで、このように、関数呼び出しで別のアイテムにhelloに引数を配置する必要があります。それ以外の場合、Timer(10.0, hello(h))を使用すると、helloは明示的に返されないため、この関数呼び出しの結果はTimerNone)に渡されます。

+0

ありがとうございます:) – sandra

関連する問題