[英]Problems communicating between Node.js and Python via stdio
I'm spawning a Node process from within a Python thread and passing data between them via stdio. 我正在从Python线程中生成Node进程,并通过stdio在它们之间传递数据。 After Python sends something to Node, Node fires up a child process and then sends the output from that child process back to Python.
Python将某些内容发送到Node之后,Node会启动一个子进程,然后将该子进程的输出发送回Python。
This works, for a few seconds and then no more data comes. 这可以工作几秒钟,然后再没有更多数据了。 However, if I kill the Node process, then suddenly all of the data comes at once.
但是,如果我终止了Node进程,那么突然所有数据都会立即出现。
I figure this is something to do with buffering but I've tried so many things and can't get it to work properly. 我认为这与缓冲有关,但是我尝试了很多事情,无法使其正常工作。
It's worth mentioning that if I run the monitor outside of Python it works fine, so this is probably something on the Python side. 值得一提的是,如果我在Python外部运行监视器,则可以正常工作,因此这可能是Python方面的事情。
Relevant Python code: 相关的Python代码:
class MonitorThread(Thread):
# *snip*
def run(self):
self.process = Popen(['node',
path.join(PACKAGE_PATH 'monitor.js')],
stdout=PIPE, stdin=PIPE, stderr=PIPE)
while self.process.poll() is None:
stdout = self.process.stdout.readline().rstrip('\n')
if stdout:
main_thread(debug, stdout)
stderr = self.process.stderr.readline().rstrip('\n')
if stderr:
main_thread(debug, stderr)
#time.sleep(0.1)
Relevant Node.js code (in CoffeeScript but even if you don't know it you get the idea): 相关的Node.js代码(在CoffeeScript中,但即使您不知道,也可以理解):
# *snip*
child = spawn cmd, options
child.stdout.on 'data', (data) ->
process.stdout.write "stdout: #{data.toString().trim()}\n"
child.stderr.on 'data', (data) ->
process.stdout.write "stderr: #{data.toString().trim()}\n"
There's a lot of other code but it's not really relevant, data is being sent and then afterwards data is being received, just only for a moment. 还有很多其他代码,但实际上并没有什么关系,先发送数据,然后再接收数据,仅一会儿。 It IS still running as when I kill it manually, the rest of the data suddenly appears.
当我手动将其杀死时,它仍在运行,其余数据突然出现。
Monitor [send] - {"wrap": false, "directories": {"src": "lib"}, "id": 0, "base_dir": "C:\\Users\\Joe\\Documents\\GitHub\\CoffeeScript-Sublime-Plugin"}
Monitor [recv] - 13:55:30 - compiled src\a.coffee
Monitor [recv] - path.exists is now called `fs.exists`.
Monitor [recv] - 13:55:30 - compiled src\b.coffee
You should also pass the end
event to close the streams and have node flush them: 您还应该传递
end
事件以关闭流并让节点刷新它们:
child = spawn cmd, options
child.stdout.pipe(process.stdout)
child.stderr.pipe(process.stdout)
child.stdout.on 'data', (data) ->
process.stdout.write "stdout: #{data.toString().trim()}\n"
child.stdout.on 'end', () ->
process.stdout.end()
child.stderr.on 'end', () ->
process.stdout.end()
An even better option would be to use Stream.pipe() . 更好的选择是使用Stream.pipe() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.