[英]Piping node.js to python
我正在尝试测试一个稍微简单的node.js到python管道,这就是非阻塞的。
到目前为止,我有以下代码
在test.js中:
for(var i = 0; i < 100; i++)
console.log("hello");
process.exit(0);
在test.py中:
import sys
from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue, Empty
def enqueue_output(out, queue):
while True:
lines = out.readline()
out.flush()
queue.put(lines)
process = Popen("node test.js", stdout=PIPE)
queue = Queue()
thread = Thread(target=enqueue_output, args=(process.stdout, queue))
thread.daemon = True # kill all on exit
thread.start()
while True:
try:
char = queue.get_nowait()
except Empty:
continue # do stuff
else:
sys.stdout.write(char)
我希望程序可以简单地输出100次hello。 但是我没有输出(运行为:)
> python test.py
您需要修改行
process = Popen("node test.js", stdout=PIPE)
至:
process = Popen(['/usr/local/bin/node', 'test.js'], stdout=PIPE)
删除process.exit(0)
。 这导致进程在对stdout的写入有机会完成之前退出,因为当stdout是管道而不是tty时,在* nix上的写入是异步的。 几乎不需要调用process.exit()
,因为该过程自然会结束,并且0仍然是默认的退出状态代码。
process.stdout
/ process.stderr
的文档最近已更新,以描述这些流将被同步或异步的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.