3

トルネードを使用しています。以下が理解しやすいことを願っています.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. それ、どうやったら出来るの?

4

1 に答える 1

1

QueuePython に付属するノンブロッキング メッセージング メカニズムである を使用します。

この回答には、別のスレッドがプロセスから出力行を読み取り、それらをキューに書き込む、非常に優れた実装があります。メイン スレッドは、ノンブロッキング方式でキューから読み取ることができます。

コメント内のリンクを提供してくれたAndrewに感謝します。

于 2012-11-06T07:12:26.503 に答える