【问题标题】:coroutine yield continue to main协程产量继续主
【发布时间】:2017-07-30 13:18:43
【问题描述】:

我正在尝试使用协程将数据发送到 NATS(nats.io 消息系统)。

当我尝试在不带参数的情况下调用此代码并使用 for 循环时,它运行良好。

但是当我添加参数时,yield nc.connect 函数不会返回任何内容并继续主函数。

如何调用带有参数的协程?

@tornado.gen.coroutine
def process_events_list(events):  
    try: 
        nc = NATS()
        parser = SafeConfigParser()
        conf = os.path.realpath(
        os.path.join(os.getcwd(),'ev_nats\\ev_nats.ini'))
        parser.read(conf)
        endpoints = ast.literal_eval(parser.get('Nats', 'Servers'))
        subject = parser.get('Nats', 'Subject')
        opts = {"servers": endpoints}
        **yield nc.connect(**opts)**  # wont connect return to main        
        for ev in events:
            yield nc.publish(subject, ev)
        yield nc.flush()
        log("Published")
    except Exception, e:
        log(e)

if __name__=='__main__': # if run directly, not called by event_dispatcher.py
   evt = ['1','2','3']
   tornado.ioloop.IOLoop.instance().run_sync(lambda : process_events_list(evt))

【问题讨论】:

    标签: python python-2.7 coroutine nats.io


    【解决方案1】:

    我会尝试进一步调试您传递给服务器的端点列表是否有效。否则,如果您可以连接到服务器,这样做应该可以工作。

    # coding: utf-8
    import tornado.ioloop
    import tornado.gen
    from nats.io.client import Client as NATS
    
    @tornado.gen.coroutine
    def main(events):
        print("Args:", events)
        nc = NATS()
    
        # Establish connection to the server.
        options = { "servers": ["nats://127.0.0.1:4222"] }
        yield nc.connect(**options)
    
        for e in events:
            yield nc.publish("example", "event:{}".format(e))
    
    if __name__ == '__main__':
        events = ['1', '2', '8']
        tornado.ioloop.IOLoop.instance().run_sync(lambda: main(events))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2020-02-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2019-09-07
      相关资源
      最近更新 更多