简体   繁体   中英

Python [child] process sending message to Node [parent] process

Python process forked by NodeJS - Alternative to process.send() for Python?

I followed the solution above but doesnt seem to work (no messages are being send by the child python code. Here is my code:

const spawn = require('child_process').spawn;

var child = spawn('python3', ['child.py'], {
    stdio:[null, null, null, 'pipe']
});

child.on('message', function(message) {
    console.log('Received message...');
    console.log(message);
});

and

# !/usr/bin/python3
import os

os.write(3, str.encode("HELLO"))

I can see what could go wrong. Please help.

I think the fourth parameter needs to be 'ipc' not 'pipe' to enable this style of message passing.

'ipc' - Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the subprocess.send() method. If the child writes JSON messages to this file descriptor, the subprocess.on('message') event handler will be triggered in the parent. If the child is a Node.js process, the presence of an IPC channel will enable process.send(), process.disconnect(), process.on('disconnect'), and process.on('message') within the child.

https://nodejs.org/api/child_process.html#child_process_options_stdio

From the description of the fork which sets this up by default (unlike spawn for other languages):

stdio | See child_process.spawn()'s stdio. When this option is provided, it overrides silent. If the array variant is used, it must contain exactly one item with value 'ipc' or an error will be thrown. For instance [0, 1, 2, 'ipc'].

https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM