NodeJS 派生的 Python 进程 - Python 的 process.send() 的替代方案?

问题描述 投票:0回答:2

我正在用 NodeJS 分叉一个 Python 脚本,当分叉时,默认情况下,NodeJS 会在这个新进程和父进程之间创建一个 IPC。

使用 NodeJS,将消息从一个孩子发送到我做的父母

process.send({msg : 'toto'})

如何使用 Python 做到这一点?

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

python node.js fork ipc
2个回答
15
投票

好吧,我找到了,终于很容易了。这只是写在正确的文件描述符上。

在 NodeJS 端参数上,像这样生成脚本:

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);
});

因为'ipc'通道是第4个参数,你必须在文件描述符3上写。 在 Python 方面:

import os

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

完成。您将在 child.on('message' 回调中收到消息。

干杯!


0
投票

在遵循@Unitech 的回答并遇到问题后,我发现发生的事情还有更多。我不确定这是否与我的 Node 版本有关,还是其他原因。 (我正在运行 v16.13.1 和 python 3.10.8)然而,消息交易的方式似乎已经改变。消息现在以 8 个字节的内容开头,还有 8 个字节,这是小端格式的消息长度。

无论如何,我已经编写了以下 python 代码,我已经成功地发送和接收消息。

import os
import json

# get the FD from ENV
NODEIPCFD = int(os.environ["NODE_CHANNEL_FD"])

def sendMessage(text):
  'sends a Node IPC message to parent proccess'
  # encode message as json string + newline in bytes
  bytesMessage = (json.dumps(text) + "\n").encode()
  # I'm not actually sure what this number is for,
  # but not including it causes problems.
  # probably encodes something to do with the 'advanced' serialization
  os.write(NODEIPCFD, int.to_bytes(1, 8, "little"))
  # send the length as an 8-byte number in little Endian format
  os.write(NODEIPCFD, len(bytesMessage).to_bytes(8, "little"))
  # send message
  os.write(NODEIPCFD, bytesMessage)


def readMessage():
  'read in next message from parent Node process via built-in node IPC'
  # read and discard 8 bytes. Again, don't know why...
  os.read(NODEIPCFD, 8)
  # read and parse 8 bytes as length in little Endian format
  length = int.from_bytes(os.read(NODEIPCFD, 8), "little")
  # read 'length' bytes and pass to json parser
  return json.loads(os.read(NODEIPCFD, length))

我在节点端使用它启动了 python 代码:

const child_process = require('node:child_process');

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

我只希望 Node 文档包含消息交易的底层过程。

© www.soinside.com 2019 - 2024. All rights reserved.