【问题标题】:python subprocess callback when updated output更新输出时的python子进程回调
【发布时间】:2012-11-06 07:00:44
【问题描述】:

我正在使用龙卷风。我希望以下内容易于理解,它正在生成一个 tcproute 进程并将输出发送到 websocket 的另一端。

class TracerouteHandler(tornado.websocket.WebSocketHandler):
  def open(self,ip):
    p = subprocess.Popen(['traceroute',ip],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while p.poll() is None: #running
      line=p.stdout.readline()
      if line!=None and len(line)>0:
        self.write_message(json.dumps({'stdout':line})) 
    self.write_message(json.dumps({'stdout':'Done! For red marked ip addresses, the location couldn\'t be determined with <a href="http://hostip.info">hostip.info</a>. If you know the correct location, please update it there.'}))

问题是由于while p.poll() is None 循环,龙卷风阻塞。此外,如果 p.stdout 中没有可读取的内容,则 p.stdout.readline 会阻塞。所以我想要某种回调机制,当我在p.stdout 中有新内容时会触发它。我该怎么做?

【问题讨论】:

标签: python asynchronous websocket subprocess tornado


【解决方案1】:

使用Queue,这是 Python 附带的一种非阻塞消息传递机制。

this answer 中有一个非常好的实现,其中一个单独的线程从进程中读取输出行,并将它们写入队列。主线程可以以非阻塞方式从队列中读取。

感谢Andrew 提供评论中的链接。

【讨论】:

  • 线程本身在 Python 中不是很好,所以我会尝试 toro 的队列。
猜你喜欢
  • 2011-02-04
  • 2021-08-30
  • 1970-01-01
  • 2023-01-19
  • 2014-09-19
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 2012-01-18
相关资源
最近更新 更多