Node.js子进程到Python进程 [英] Node.js child process to Python process

查看:184
本文介绍了Node.js子进程到Python进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将文本从node.js子进程发送到python进程. 我的虚拟节点客户端看起来像

I must send text from a node.js child process to a python process. My dummy node client looks like

var resolve = require('path').resolve;
var spawn = require('child_process').spawn;

data = "lorem ipsum"

var child = spawn('master.py', []);

var res = '';
child.stdout.on('data', function (_data) {
    try {
        var data = Buffer.from(_data, 'utf-8').toString();
        res += data;
    } catch (error) {
        console.error(error);
    }
});
child.stdout.on('exit', function (_) {
    console.log("EXIT:", res);
});
child.stdout.on('end', function (_) {
    console.log("END:", res);
});
child.on('error', function (error) {
    console.error(error);
});

child.stdout.pipe(process.stdout);

child.stdin.setEncoding('utf-8');
child.stdin.write(data + '\r\n');

Python进程master.py

#!/usr/bin/env python

import sys
import codecs

if sys.version_info[0] >= 3:
    ifp = codecs.getreader('utf8')(sys.stdin.buffer)
else:
    ifp = codecs.getreader('utf8')(sys.stdin)

if sys.version_info[0] >= 3:
    ofp = codecs.getwriter('utf8')(sys.stdout.buffer)
else:
    ofp = codecs.getwriter('utf8')(sys.stdout)

for line in ifp:
    tline = "<<<<<" + line + ">>>>>"
    ofp.write(tline)

# close files
ifp.close()
ofp.close()

我必须使用utf-8编码的输入阅读器,所以我使用的是sys.stdin,但似乎当node.js使用child.stdin.write(data + '\r\n');写入子进程stdin时,<for line in ifp:

I must use a utf-8 encoded input reader so I'm using a sys.stdin, but it seems that when node.js writes to child process stdin using child.stdin.write(data + '\r\n');, this will not be read by sys.stdin in for line in ifp:

推荐答案

在最终调用child.stdin.write()之后,您需要在Node程序中调用child.stdin.end().在调用end()之前,child.stdin可写流会将写入的数据保存在缓冲区中,因此Python程序将看不到它.请参阅 https:中的缓冲讨论: //nodejs.org/docs/latest-v8.x/api/stream.html#stream_buffering 了解详情.

You'll need to call child.stdin.end() in the Node program after the final call to child.stdin.write(). Until end() is called, the child.stdin writable stream will hold the written data in a buffer, so the Python program won't see it. See the Buffering discussion in https://nodejs.org/docs/latest-v8.x/api/stream.html#stream_buffering for details.

(如果您向stdin中写入大量数据,则写缓冲区最终将填充到一个点,在该点处,所存储的数据将自动清除到Python程序中.然后该缓冲区将再次开始收集数据. c9>需要进行调用以确保清除了写入数据的最后部分,并且还具有向子进程指示不再在该流上发送任何数据的作用.)

(If you write lots of data into stdin then the write buffer will eventually fill to a point where the accumulated data will be flushed out automatically to the Python program. The buffer will then begin again to collect data. An end() call is needed to make sure that the final portion of the written data is flushed out. It also has the effect of indicating to the child process that no more data will be sent on this stream.)

这篇关于Node.js子进程到Python进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆