Exception in thread Thread-4:

Chris Angelico rosuav at gmail.com
Tue May 5 05:52:10 EDT 2015


On Tue, May 5, 2015 at 7:23 PM, david jhon <djhon9813 at gmail.com> wrote:
> from threading import Timer, Lock
>
> class miTestClass(EventMixin):
>     def __init__(self, t, r, bw):
>          self.statMonitorLock = Lock() #to lock the multi access threads
>          self.statMonitorLock.acquire()
>          statMonitorTimer = Timer(10.0, self._collectFlowStats()) #timer to
> collect stats
>          statMonitorTimer.start()
>
> but I am getting following error:
>
> Exception in thread Thread-4:
> Traceback (most recent call last):
>   File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
>     self.run()
>   File "/usr/lib/python2.7/threading.py", line 1082, in run
>     self.function(*self.args, **self.kwargs)
> TypeError: 'NoneType' object is not callable

The Timer() class will call a function when it's ready. To use that,
you want to pass it a function. Try putting these two lines of code
into your __init__ function:

print(self._collectFlowStats)
print(self._collectFlowStats())

(Aside: This is something I like to call "IIDPIO debugging": If In
Doubt, Print It Out. You sometimes have more sophisticated debugging
techniques available, but you hardly ever are unable to basic 'print',
in some form or another. It's incredibly useful.)

The first one will print out something like this:

<bound method miTestClass._collectFlowStats of <__main__.miTestClass
object at 0x12345678>>

The second will actually call that function (which may or may not do
anything visible), and then print out:

None

If you change your _collectFlowStats function a bit, you can see even
more of what's happening. Something like this:

def _collectFlowStats(self):
    print("_collectFlowStats has been called. Returning 42...")
    return 42

Then you'll see that it gets called, and does its print, and then 42
gets printed out at the end.

In your case, simply removing the parentheses from
self._collectFlowStats should do what you want - the Timer constructor
will be passed a function (in this case, a bound method, but same
same), and that function won't be called until the timer is up.

Hope that helps!

ChrisA



More information about the Python-list mailing list