![](/img/trans.png)
[英]How to call a class method using an instance of a different class in Python?
[英]How did I call different class instance in a class method?
我正在使用zerorpc構建發布訂閱NAT斷路器,並在昨天完成了任務。 現在,我正在嘗試修改代碼,以便使用Sander Marechal的代碼示例將發布程序作為守護程序運行。
這是我的Publisher.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import zerorpc
import os, sys, time
from daemon import Daemon
class publisherd(Daemon):
def run(self):
publisher = zerorpc.Publisher()
publisher.bind("tcp://0.0.0.0:8888")
# Start RPC Server
s = LocalForwarder()
s.bind("tcp://0.0.0.0:4242")
s.run()
class LocalForwarder(zerorpc.Server):
def pub(self, domain, testcase_pk, testresult_pk):
print domain, testcase_pk, testresult_pk
publisher.add(domain, testcase_pk, testresult_pk)
print 'Send to dispacher'
if __name__ == "__main__":
daemon = publisherd('/tmp/publisher.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
我建立了一個autosender.py進行測試
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import zerorpc
import os, sys
time = 0
sleep = 10
for i in range(1,10,1):
ts_dispatcher_name = "KS-1"
testsuite_id = i
tr_pk = time
c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
c.pub(ts_dispatcher_name, testsuite_id, tr_pk)
print ts_dispatcher_name, testsuite_id, tr_pk
time += sleep
os.system("sleep %s" %sleep)
但是測試時出現以下錯誤消息:
File "publisher_d.py", line 21, in pub
publisher.add(domain, testcase_pk, testresult_pk)
NameError: global name 'publisher' is not defined
似乎LocalForwarder無法確認發布者實例,但是我不知道為什么會發生錯誤? 我該如何糾正該錯誤?
您似乎希望發布者成為全局變量。 為此,您需要嘗試以下操作:
my_global = None
def x():
global my_global
my_global = 1
def y():
print(my_global)
默認情況下,您創建的發布者var在本地范圍內適用於該方法-這是分配時的默認值。 global
關鍵字允許您在全局范圍級別設置該變量。 僅引用值的函數不需要global
關鍵字。
您必須將發布者實例傳遞給LocalFowarder
實例,即:
class Publisherd(Daemon):
def run(self):
publisher = zerorpc.Publisher()
publisher.bind("tcp://0.0.0.0:8888")
# Start RPC Server
s = LocalForwarder(publisher)
s.bind("tcp://0.0.0.0:4242")
s.run()
class LocalForwarder(zerorpc.Server):
def __init__(self, publisher, *args, **kw):
super(LocalForwarder, self).__init__(*args, **kw)
self.publisher = publisher
def pub(self, domain, testcase_pk, testresult_pk):
print domain, testcase_pk, testresult_pk
self.publisher.add(domain, testcase_pk, testresult_pk)
print 'Send to dispacher'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.