我是如何在类方法中调用不同的类实例的?

时间:2015-05-29 13:24:16

标签: python class instance

我正在使用zerorpc构建一个pub-sub NAT断路器并在昨天完成它。现在我正在尝试修改我的代码,以便使用Sander Marechal的code sample将发布者作为守护进程运行。

这是我的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无法识别发布者实例,但我无法弄清楚错误发生的原因?我该怎么做才能纠正这个错误?

2 个答案:

答案 0 :(得分:0)

您希望发布商成为全局变量。要做到这一点,你需要尝试这样的事情:

my_global = None

def x():
    global my_global
    my_global = 1

def y():
    print(my_global)

默认情况下,您创建的发布者var是本地作用于该方法的 - 这是分配时的默认值。 global关键字允许您在全局范围级别设置该变量。仅引用该值的函数不需要global关键字。

答案 1 :(得分:0)

您必须将发布商实例传递到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'