gpt4 book ai didi

javascript - Node.js 和 Python 通过 stdio 进行通信时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:02 24 4
gpt4 key购买 nike

我从 Python 线程中生成一个 Node 进程,并通过 stdio 在它们之间传递数据。 Python 向 Node 发送内容后,Node 会启动一个子进程,然后将该子进程的输出发送回 Python。

这有效,持续几秒钟,然后就不再有数据了。但是,如果我终止 Node 进程,那么突然所有数据都会立即出现。

我认为这与缓冲有关,但我尝试了很多方法,但无法让它正常工作。

值得一提的是,如果我在 Python 之外运行监视器,它可以正常工作,因此这可能是 Python 端的问题。

相关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)

相关 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"

还有很多其他代码,但它们并不真正相关,正在发送数据,然后接收数据,只是一会儿。它仍在运行,因为当我手动杀死它时,其余数据突然出现。

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
  • 我尝试过 util.pump()
  • 我已经尝试过,使用 spawn() 调用,stdio: 'inherit'
  • 我尝试先等待“drain”事件,然后再发送更多数据。

最佳答案

您还应该传递 end 事件来关闭流并让 Node 刷新它们:

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()

更好的选择是使用 Stream.pipe() .

关于javascript - Node.js 和 Python 通过 stdio 进行通信时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11669925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com