Python process forked by NodeJS - Alternative to p

2019-03-30 00:58发布

问题:

I'm forking a Python script with NodeJS and when forked, by default, NodeJS create an IPC between this new process and the parent.

With NodeJS, to send message from a child to the parent I do process.send({msg : 'toto'})

How can I do that with Python ?

http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

回答1:

Ok I found it, finally is quite easy. It's only about writing on the right file descriptor.

On the NodeJS side parameter, spawn your script like that :

var child = child_process.spawn('python', ['hello.py'], {
  stdio:[null, null, null, 'ipc']
});

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

As the 'ipc' channel is the 4rd parameter, you will have to write on the filedescriptor 3. On the Python side :

import os

os.write(3, '{"dt" : "This is a test"}\n', "utf8")

Done. You will receive the message on the child.on('message' callback.

Cheers !