我有非常简单的worker代码,可能犯了一些愚蠢的错误。
class BingWorker(object):
def __init__(self):
self.gm_worker = gearman.GearmanWorker(['localhost:4730'])
completed_job_request = self.gm_worker.register_task('bingmedia', callBing)
def callBing(self, gearman_worker, gearman_job):
print "In worker ", gearman_job.data
return "Kools"
def run(self):
self.gm_worker.work()
if __name__ == '__main__':
BingWorker().run()
给
Traceback (most recent call last):
File "worker.py", line 16, in <module>
BingWorker().run()
File "worker.py", line 6, in __init__
completed_job_request = self.gm_worker.register_task('bingmedia', callBing)
NameError: global name 'callBing' is not defined
有什么提示吗? 示例与 http://gearman.org/examples/reverse/的 Python 示例非常相似。 只需放入类结构
改进的代码:
class BingWorker(object):
def __init__(self):
self.gm_worker = gearman.GearmanWorker(['localhost:4730'])
def callBing(self, gearman_worker, gearman_job):
print "In worker ", gearman_job.data
return "Kools"
def run(self):
completed_job_request = self.gm_worker.register_task('bingmedia', self.callBing)
self.gm_worker.work()
if __name__ == '__main__':
BingWorker().run()
您需要将callBing
更改为self.callBing
,最好将注册移动到run方法的第一行而不是__init__
方法。
拳头是因为callBing
是对缺少的全局的引用,而self.callBing
是对类方法的引用。第二个是因为您可能会在 init 完成之前接到self.callBing
的电话,这将是个坏消息。