[英]python: Threading issues while backporting to v2.4 from v2.7
I had the following code that works fine with python 2.7+ 我有以下与python 2.7+兼容的代码
class Worker(threading.Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None, onCompleteCb=None):
self.__onCompleteCb = onCompleteCb
self.__name = name
super(Worker, self).__init__(group, target, name, args, kwargs, verbose)
def getName(self):
return self.__name
def run(self):
try:
super(Worker, self).run()
if self.__onCompleteCb is not None: self.__onCompleteCb(self.__name)
except Exception, e:
if self.__onCompleteCb is not None: self.__onCompleteCb(self.__name, failed=True, exception=e)
But I found out recently my code should support versions starting from 2.4: In the above code, run gets called but when it calls super(Worker, self).run()
, I see the following error 但是我最近发现我的代码应该支持从2.4开始的版本:在上面的代码中,run被调用,但是当它调用
super(Worker, self).run()
,我看到了以下错误
TypeError: threadTargMethod() argument after ** must be a dictionary
Should I call super
differently in python 2.4? 我应该在python 2.4中调用
super
吗?
Solution I have to start the thread in the following way: 解决方案我必须以以下方式启动线程:
Worker(target=threadTargMethod, name="thread1", args=(), kwargs={}).start()
In v2.7 I was starting the following way and it works 在v2.7中,我开始采用以下方式,并且可以正常工作
Worker(target=threadTargMethod, name="thread1").start()
I would suggest changing your code to: 我建议将您的代码更改为:
class Worker(threading.Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, verbose=None, onCompleteCb=None):
...
super(Worker, self).__init__(group=group, target=target, name=name,
args=args, kwargs=kwargs)
In other words: 换一种说法:
Make the default for kwargs
an empty dict (which matches the docs - you seem to have got lucky with 2.7) 将
kwargs
的默认值设为空dict(与文档匹配-您似乎很幸运使用2.7)
Don't include the verbose
parameter (not supported in 2.4 or 2.7 - no idea what was happening there) 不要包含
verbose
参数(2.4或2.7不支持-不知道那里发生了什么)
Make names explicit 使名称明确
With that change you can continue to start with 进行更改后,您可以继续
Worker(target=threadTargMethod, name="thread1").start()
because kwargs
will be set correctly by default. 因为默认情况下会正确设置
kwargs
。
I have to start the thread in the following way in v2.4: 我必须在v2.4中以以下方式启动线程:
Worker(target=threadTargMethod, name="thread1", args=(), kwargs={}).start()
In v2.7 I was starting the following way and it works 在v2.7中,我开始采用以下方式,并且可以正常工作
Worker(target=threadTargMethod, name="thread1").start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.