[英]NodeJS child_process stdout, if process is waiting for stdin
[英]NodeJS: Send message to persistent child process's stdin without human interaction?
我嘗試將自定義消息發送到持久子進程的標准輸入。 子進程不是節點進程,而是任意程序。 子進程使用 REPL 交互式提示來接受用戶輸入並將結果打印到標准輸出,標准輸出通過管道返回到父進程。 我需要能夠不斷地向孩子發送消息並始終如一地獲得結果。
我知道我們可以使用fork()
向基於 NodeJS 的子進程發送消息,但這不適用於非節點進程。
我最初的嘗試是允許用戶從父進程的 stdin 輸入消息,並將其通過其子進程進行管道傳輸。 這有效,但最終不是我想要的。
hello_childstdin.js
const {join} = require('path');
const {spawn} = require('child_process');
const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);
process.stdin.pipe(child.stdin);
child.stdout.on('data', (data) => {
console.log(`child stdout: \n${data}`);
});
child.stderr.on('data', (data) => {
console.log(`child stderr: \n${data}`);
});
hello_childstdin.py
while True:
cmd = input('Enter command here (hello, bye, do it):')
print('cmd: {}'.format(cmd))
msg = cmd+': done\n' if cmd in ('hello', 'bye', 'do it') else 'undefined cmd: {}'.format(cmd)
with open('/path/to/hello_childstdin.txt', 'a') as f:
f.write(msg)
print('msg: {}'.format(msg))
但是,我真正想要的是在沒有人工干預的情況下直接向子進程的標准輸入發送消息?
我嘗試了以下但失敗了。
hello_childstdin.js
const {join} = require('path');
const {spawn} = require('child_process');
const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);
process.stdin.pipe(child.stdin);
// Trying to write to parent process stdin
process.stdin.write('hello\n');
child.stdout.on('data', (data) => {
console.log(`child stdout: \n${data}`);
});
child.stderr.on('data', (data) => {
console.log(`child stderr: \n${data}`);
});
hello_childstdin.js
const {join} = require('path');
const {spawn} = require('child_process');
const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);
process.stdin.pipe(child.stdin);
// Trying to write to parent process stdin
child.stdin.write('hello\n');
child.stdout.on('data', (data) => {
console.log(`child stdout: \n${data}`);
});
child.stderr.on('data', (data) => {
console.log(`child stderr: \n${data}`);
});
看到 child.stdin 的文檔解釋:
如果子進程正在等待讀取其所有輸入,則在通過 end() 關閉此流之前,它不會繼續。
然后我在我的父進程中嘗試了以下操作。
// ... same as above ...
child.stdin.write('hello\n');
child.stdin.end();
// ... same as above ...
這結束子並且不寫消息。
與未分叉的子進程進行雙工通信的正確方法是什么?
想通了:我可以將可讀流推送給孩子。
...
const stream = require('stream');
...
var stdinStream = new stream.Readable();
stdinStream.push('hello\n'); // Add data to the internal queue for users of the stream to consume
stdinStream.pipe(child.stdin);
感謝這個答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.