当前位置: 首页>>代码示例>>Python>>正文


Python Context.term方法代码示例

本文整理汇总了Python中zmq.Context.term方法的典型用法代码示例。如果您正苦于以下问题:Python Context.term方法的具体用法?Python Context.term怎么用?Python Context.term使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在zmq.Context的用法示例。


在下文中一共展示了Context.term方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: HomeBase

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class HomeBase(Thread):

    def __init__(self):
        super(HomeBase, self).__init__(name="HomeBase")
        self.context = Context()
        self.pull = self.context.socket(PULL)
        self.pull.bind("tcp://*:7001")
        self._shutdown = False
        self.poller = Poller()
        self.poller.register(self.pull, POLLIN)

    def cleanup(self):
        self.pull.close()
        self.context.term()

    def run(self):
        while True:
            socks = dict(self.poller.poll(timeout=1))
            if socks.get(self.pull) == POLLIN:
                msg = self.pull.recv()
                msg += ", WORK RECEIVED "
                print msg
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:27,代码来源:pipeline_sink.py

示例2: Zmq_broker

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class Zmq_broker(BaseModule):
    context = None
    s_pub = None
    pub_endpoint = None
    serialize_to = None
    serialize = None

    def __init__(self, mod_conf, pub_endpoint, serialize_to):
        from zmq import Context, PUB

        BaseModule.__init__(self, mod_conf)
        self.pub_endpoint = pub_endpoint
        self.serialize_to = serialize_to
        logger.info("[Zmq Broker] Binding to endpoint " + self.pub_endpoint)

        # This doesn't work properly in init()
        # sometimes it ends up beings called several
        # times and the address becomes already in use.
        self.context = Context()
        self.s_pub = self.context.socket(PUB)
        self.s_pub.bind(self.pub_endpoint)

        # Load the correct serialization function
        # depending on the serialization method
        # chosen in the configuration.
        if self.serialize_to == "msgpack":
            from msgpack import Packer

            packer = Packer(default=encode_monitoring_data)
            self.serialize = lambda msg: packer.pack(msg)
        elif self.serialize_to == "json":
            self.serialize = lambda msg: json.dumps(msg, cls=SetEncoder)
        else:
            raise Exception("[Zmq Broker] No valid serialization method defined (Got " + str(self.serialize_to) + ")!")

    # Called by Broker to say 'let's prepare yourself guy'
    def init(self):
        logger.info("[Zmq Broker] Initialization of the Zmq broker module")

    # Publish to the ZeroMQ socket
    # using the chosen serialization method
    def publish(self, msg, topic=""):
        from zmq import SNDMORE

        data = self.serialize(msg)
        self.s_pub.send(topic, SNDMORE)
        self.s_pub.send(data)

    # An host check have just arrived, we UPDATE data info with this
    def manage_brok(self, b):
        logger.debug("[Zmq Broker] Got broker update: " + str(b.data))

        # Publish update data to the ZeroMQ endpoint.
        msg = b.data
        self.publish(msg, b.type)

    # Properly close down this thing.
    def do_stop(self):
        self.s_pub.close()
        self.context.term()
开发者ID:shinken-debian-modules,项目名称:shinken-mod-zmq,代码行数:62,代码来源:module.py

示例3: Listener

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class Listener(Thread):
    def __init__(self):
        super(Listener, self).__init__(name="Listener")

        self._shutdown = False
        self.context = Context()
        self.sub = self.context.socket(SUB)
        self.sub.bind('tcp://*:7000')
        self.sub.setsockopt(SUBSCRIBE, "")

        self.poller = Poller()
        self.poller.register(self.sub, POLLIN)

    def cleanup(self):
        self.sub.close()
        self.context.term()

    def run(self):
        while True:
            socks = dict(self.poller.poll(timeout=1))
            if socks.get(self.sub) == POLLIN:
                msg = self.sub.recv(flags=NOBLOCK)
                print msg
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:28,代码来源:listener.py

示例4: HomeBase

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class HomeBase(Thread):

    def __init__(self):
        super(HomeBase, self).__init__(name="HomeBase")
        self.context = Context()
        self.pull = self.context.socket(PULL)
        self.pull.bind("tcp://*:7001")
        self._shutdown = False
        self.poller = Poller()
        self.poller.register(self.pull, POLLIN)
        for th in t_enum():
            if th.name == "MainThread":
                self.mainthread = th

    def cleanup(self):
        print "Home exiting..."
        self.pull.close()
        self.context.term()

    def run(self):
        while True:
            if not self.mainthread.is_alive():
                self._shutdown = True
                break
            socks = dict(self.poller.poll(timeout=1))
            if socks.get(self.pull) == POLLIN:
                msg = self.pull.recv(flags=NOBLOCK)
                msg += ", WORK RECEIVED "
                print msg
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:34,代码来源:pipeline_producer.py

示例5: DrillingWell

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class DrillingWell(Thread):

    def __init__(self):
        super(DrillingWell, self).__init__(name="DrillingWell")
        self.context = Context()
        self.push = self.context.socket(PUSH)
        self.push.bind("tcp://*:7000")
        self._shutdown = False
        for th in t_enum():
            if th.name == "MainThread":
                self.mainthread = th

    def cleanup(self):
        print "Producer exiting..."
        self.push.close()
        self.context.term()

    def run(self):
        count = 0
        while True:
            if not self.mainthread.is_alive():
                self._shutdown = True
                break
            sleep(0.01)
            count += 1
            self.push.send("SOMETHING " + str(count))
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:31,代码来源:pipeline_producer.py

示例6: Leatherneck

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class Leatherneck(Thread):

    def __init__(self):
        super(Leatherneck, self).__init__(name="Leatherneck")
        self.context = Context()
        self.pull = self.context.socket(PULL)
        self.pull.connect("tcp://localhost:7000")
        self.push = self.context.socket(PUSH)
        self.push.connect("tcp://localhost:7001")
        self.poller = Poller()
        self.poller.register(self.pull, POLLIN)
        self._shutdown = False
        for th in t_enum():
            if th.name == "MainThread":
                self.mainthread = th

    def cleanup(self):
        print "Workers exiting..."
        self.push.close()
        self.pull.close()
        self.context.term()

    def run(self):
        while True:
            if not self.mainthread.is_alive():
                self._shutdown = True
                break
            socks = dict(self.poller.poll(timeout=1))
            if socks.get(self.pull) == POLLIN:
                msg = self.pull.recv(flags=NOBLOCK)
                msg += " WORK COMPLETE, " + str(time())
                self.push.send(msg, flags=NOBLOCK)
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:37,代码来源:pipeline_producer.py

示例7: Leatherneck

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class Leatherneck(Thread):

    def __init__(self):
        super(Leatherneck, self).__init__(name="Leatherneck")
        self.context = Context()
        self.pull = self.context.socket(PULL)
        self.pull.connect("tcp://localhost:7000")
        self.push = self.context.socket(PUSH)
        self.push.connect("tcp://localhost:7001")
        self.poller = Poller()
        self.poller.register(self.pull, POLLIN)
        self._shutdown = False

    def cleanup(self):
        self.push.close()
        self.pull.close()
        self.context.term()

    def run(self):
        while True:
            socks = dict(self.poller.poll(timeout=1))
            if socks.get(self.pull) == POLLIN:
                msg = self.pull.recv()
                msg += " WORK COMPLETE, " + str(time())
                self.push.send(msg)
            if self._shutdown:
                break
        self.cleanup()
开发者ID:dcolish,项目名称:Presentations,代码行数:30,代码来源:pipeline_worker.py

示例8: ZmqFactory

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class ZmqFactory(object):
    """
    I control individual ZeroMQ connections.

    Factory creates and destroys ZeroMQ context.

    :var reactor: reference to Twisted reactor used by all the connections
    :var ioThreads: number of IO threads ZeroMQ will be using for this context
    :vartype ioThreads: int
    :var lingerPeriod: number of milliseconds to block when closing socket
        (terminating context), when there are some messages pending to be sent
    :vartype lingerPeriod: int

    :var connections: set of instanciated :class:`ZmqConnection`
    :vartype connections: set
    :var context: ZeroMQ context
    """

    reactor = reactor
    ioThreads = 1
    lingerPeriod = 100

    def __init__(self):
        """
        Constructor.

        Create ZeroMQ context.
        """
        self.connections = set()
        self.context = Context(self.ioThreads)

    def __repr__(self):
        return "ZmqFactory()"

    def shutdown(self):
        """
        Shutdown factory.

        This is shutting down all created connections
        and terminating ZeroMQ context. Also cleans up
        Twisted reactor.
        """
        for connection in self.connections.copy():
            connection.shutdown()

        self.connections = None

        self.context.term()
        self.context = None

    def registerForShutdown(self):
        """
        Register factory to be automatically shut down
        on reactor shutdown.

        It is recommended that this method is called on any
        created factory.
        """
        reactor.addSystemEventTrigger('during', 'shutdown', self.shutdown)
开发者ID:brunsgaard,项目名称:txZMQ,代码行数:61,代码来源:factory.py

示例9: ZmqSubscriber

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class ZmqSubscriber(HiddenSubscriber):
    """ Subscriber class subscribing to a certain topic

        Attributes:
           context (zmq.Context):
           socket (Socket): Socket object of ZMQ context
           topic (String): Topic subscriber subscribes to
    """
    def __init__(self, url, topic):
        """ Initializes object

            Args:
                url (String): url to publish messages to
                topic (String): Topic to publish messages under
        """
        super(ZmqSubscriber, self).__init__(url)
        self._context = Context()
        self._socket = self._context.socket(SUB)
        self._socket.setsockopt(SUBSCRIBE, topic)
        self._socket.setsockopt(RCVTIMEO, 500) # Wait 500ms for message to arrive
        self._socket.connect(url)
        self._logger = logging.getLogger('ZeromqSubscriber')

    def receive(self):
        """ Receives a message

            Returns:
                String
        """
        topic, message = self._socket.recv_multipart()
        return message

    def __enter__(self):
        """ Statement used for the `` with ... as ...:`` returns
            the object to use in the ``with`` block

            Returns:
                ZmqSubscriber
        """
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        """ Executed when leaving ``with`` block, regardless whether
            because of an exception or normal program flow
        """
        self._socket.close()
        self._context.term()
开发者ID:PaddyK,项目名称:biosi,代码行数:49,代码来源:zeromqcomponents.py

示例10: ZmqPublisher

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class ZmqPublisher(HiddenPublisher):
    """ Publisher class publishing messages to a certain topic to an url

        Attributes:
            context (zmq.Context):
            socket (Socket): Socket object of ZMQ context
            topic (String): Topic publisher publishs to
    """
    def __init__(self, url, topic):
        """ Initializes object

            Args:
                url (String): url to publish messages to
                topic (String): Topic to publish messages under
        """
        super(ZmqPublisher, self).__init__(topic)
        self._context = Context()
        self._socket = self._context.socket(PUB)
        self._socket.bind(url)
        self._logger = logging.getLogger('ZeromqPublisher')

    def publish(self, message):
        """ Publishes message

            Args:
                message (String): Message to publish
        """
        self._socket.send_multipart([self.topic, message])

    def __enter__(self):
        """ Statement used for the `` with ... as ...:`` returns
            the object to use in the ``with`` block

            Returns:
                ZmqPublisher
        """
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        """ Executed when leaving ``with`` block, regardless whether
            because of an exception or normal program flow
        """
        self._socket.close()
        self._context.term()
开发者ID:PaddyK,项目名称:biosi,代码行数:46,代码来源:zeromqcomponents.py

示例11: ZmqContext

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class ZmqContext(object):
    """Provides a singleton wrapper for a ZeroMQ context"""
    self_ = None
    def __init__(self, iothreads):
        assert not ZmqContext.self_
        self._context = Context(iothreads)

    def __del__(self):
        self._context.term()

    def socket(self, socket_type):
        """Creates and returns a socket of the given type"""
        return self._context.socket(socket_type)

    @staticmethod
    def instance(iothreads=4):
        """Returns the singleton instance of the ZeroMQ context"""
        if not ZmqContext.self_:
            ZmqContext.self_ = ZmqContext(iothreads)
        return ZmqContext.self_
开发者ID:lcls-spi,项目名称:hummingbird,代码行数:22,代码来源:zmqcontext.py

示例12: Context

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
            print "%s exiting..." % self.name
        finally:
            self.cleanup()

context = Context()

heart = Heartbeat(context, name="Heartbeat Thread")
stethoscope = Stethoscope(context, name="Stethoscope Thread")


for t in (heart, stethoscope):
    t.start()

while True:
    try:
        # call thread.join to keep some control in the main thread
        while (heart.is_alive() or
               stethoscope.is_alive()):
            heart.join(timeout=0.1)
            stethoscope.join(timeout=0.1)

    except KeyboardInterrupt:
        shutdown.set()
        while (heart.is_alive() or
               stethoscope.is_alive()):
            heart.join(timeout=0.1)
            stethoscope.join(timeout=0.1)

        context.term()
        break
开发者ID:dcolish,项目名称:Presentations,代码行数:32,代码来源:spike.py

示例13: Context

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
#!/usr/bin/env python
from json import dumps
from msgpack import packb, unpackb
from sys import argv
from zmq import Context, REQ

ctx = Context()
sock = ctx.socket(REQ)
sock.connect("ipc:///var/run/pcma.socket")

sock.send(packb(argv[1:]))
ret, out = unpackb(sock.recv(), encoding='utf-8')

if ret:
    print(dumps(out))
else:
    raise Exception(out)

sock.close()
ctx.term()
开发者ID:davidpoblador,项目名称:pcma,代码行数:22,代码来源:client.py

示例14: ZmqContextManager

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class ZmqContextManager(object):
    """
    I control individual ZeroMQ connections.

    Factory creates and destroys ZeroMQ context.

    :var reactor: reference to Twisted reactor used by all the connections
    :var ioThreads: number of IO threads ZeroMQ will be using for this context
    :vartype ioThreads: int
    :var lingerPeriod: number of milliseconds to block when closing socket
        (terminating context), when there are some messages pending to be sent
    :vartype lingerPeriod: int

    :var connections: set of instantiated :class:`ZmqConnection`
    :vartype connections: set
    :var context: ZeroMQ context
    """

    reactor = reactor
    ioThreads = 1
    lingerPeriod = 100
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super(ZmqContextManager, cls).__new__(cls)
            cls._instance.initialized = False
        return cls._instance

    def __init__(self):
        """
        Constructor.

        Create ZeroMQ context.
        """
        if not self.initialized:
            self.initialized = True
            self.connections = set()
            self.context = Context(self.ioThreads)
            reactor.addSystemEventTrigger('during', 'shutdown', self.shutdown)

    def __repr__(self):
        return "ZmqContextManager(%d threads)" % self.ioThreads

    def shutdown(self):
        """
        Shutdown factory.

        This is shutting down all created connections
        and terminating ZeroMQ context. Also cleans up
        Twisted reactor.
        """
        if not self.initialized:
            return
        self.initialized = False
        for connection in self.connections.copy():
            connection.shutdown()

        self.connections = None
        self.context.term()
        self.context = None
开发者ID:2php,项目名称:veles,代码行数:63,代码来源:manager.py

示例15: TestClient

# 需要导入模块: from zmq import Context [as 别名]
# 或者: from zmq.Context import term [as 别名]
class TestClient(unittest.TestCase):
    def setUp(self):
        self.context = Context()
        self.start_router_sockets()

    def tearDown(self):
        self.close_sockets()
        self.context.term()

    def start_router_sockets(self):
        self.api = self.context.socket(REP)
        self.broadcast = self.context.socket(PUB)
        self.api.bind(API_BIND_ADDRESS)
        self.broadcast.bind(BROADCAST_BIND_ADDRESS)

    def close_sockets(self):
        self.api.close()
        self.broadcast.close()

    def test_connect_raises_ValueError_when_no_communication_channel_is_specified(self):
        client = Client()
        with self.assertRaises(ValueError):
            client.connect()

    def test_api_methods_should_raise_RuntimeError_if_not_connected_to_api(self):
        client = Client()
        client.connect(broadcast=BROADCAST_ADDRESS)
        with self.assertRaises(RuntimeError):
            client.send_api_request({'command': 'get configuration'})
        with self.assertRaises(RuntimeError):
            client.get_api_reply()
        with self.assertRaises(RuntimeError):
            client.api_poll(timeout=1) # milliseconds
        with self.assertRaises(RuntimeError):
            client.disconnect_api()

    def test_broadcast_methods_should_raise_RuntimeError_if_not_connected_to_broadcast(self):
        client = Client()
        client.connect(api=API_ADDRESS)
        with self.assertRaises(RuntimeError):
            client.broadcast_subscribe('42')
        with self.assertRaises(RuntimeError):
            client.broadcast_unsubscribe('42')
        with self.assertRaises(RuntimeError):
            client.broadcast_poll(timeout=1) # milliseconds
        with self.assertRaises(RuntimeError):
            client.broadcast_receive()
        with self.assertRaises(RuntimeError):
            client.disconnect_broadcast()

    def test_send_api_request(self):
        client = Client()
        client.connect(api=API_ADDRESS)
        client.send_api_request({'command': 'get configuration'})
        if not self.api.poll(TIMEOUT):
            self.fail('Timeout wainting for API command')
        message = self.api.recv_json()
        self.assertEqual(message, {'command': 'get configuration'})

    def test_get_api_reply(self):
        client = Client()
        client.connect(api=API_ADDRESS)
        client.send_api_request({'command': 'get configuration'})
        if not self.api.poll(TIMEOUT):
            self.fail('Timeout wainting for API command')
        self.api.recv_json()
        self.api.send_json({'configuration': 'spam eggs ham'})
        message = client.get_api_reply() # what if it hangs?
        self.assertEqual(message, {'configuration': 'spam eggs ham'})

    def test_api_poll(self, timeout=0):
        client = Client()
        client.connect(api=API_ADDRESS)
        client.send_api_request({'command': 'get configuration'})
        if not self.api.poll(TIMEOUT):
            self.fail('Timeout waiting for API message')
        self.api.recv_json()
        start_time = time.time()
        result = client.api_poll(TIMEOUT)
        end_time = time.time()
        self.assertFalse(result)
        # there is no message, should wait for the entire TIMEOUT
        total_time = (end_time - start_time) * 1000 # milliseconds
        self.assertTrue(TIMEOUT <= total_time <= 1.1 * TIMEOUT)

        self.api.send_json({'configuration': 'spam eggs ham'})
        start_time = time.time()
        result = client.api_poll(TIMEOUT)
        end_time = time.time()
        self.assertTrue(result)
        # poll should return almost immediatly (there is a message)
        total_time = (end_time - start_time) * 1000 # milliseconds
        self.assertTrue(total_time < TIMEOUT)

    def test_broadcast_subscribe_poll_and_receive(self):
        client = Client()
        client.connect(broadcast=BROADCAST_ADDRESS)
        client.broadcast_subscribe('spam')
        time.sleep(TIMEOUT / 1000.0) # wait for subscribe to take effect

#.........这里部分代码省略.........
开发者ID:NAMD,项目名称:pypelinin,代码行数:103,代码来源:test_client.py


注:本文中的zmq.Context.term方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。