使用 'child-process' 从 python 脚本中检索数据在正常的 node.js 脚本中有效,但在必需的脚本中无效

Retrieving data from python script using 'child-process' works in normal node.js script, but not in a required script

我正在制作一个 node.js 应用程序,我需要将数据发送到一个 python 脚本,它会在其中执行一些计算。然后我需要将数据从 python 脚本返回到 discord.js 命令脚本 command.js,我从主脚本 运行 index.js。 我发送需要使用 child_process 模块计算的数据:

function func1(arg1, arg2){
    let spawn = require('child_process').spawn
    const pythonProcess = spawn('python',['t1.py', arg1, arg2]);
}

然后我使用 sys 模块检索并处理 python 中的数据,如下所示:

import sys

a = sys.argv[1]
b = sys.argv[2]

print(int(a) + int(b))
sys.stdout.flush()

在 python 脚本 t1.py 中处理数据后,我像这样检索它并尝试记录它(问题是当我 运行主脚本):

pythonProcess.stdout.on('data', (data) => {
    console.log(Number(data))
});

然后我使用 module.exports:

将结果数据从 command.js 发送到 index.js
module.exports = {
    'func1': func1
}

最后我 requirecommand.js 脚本导出的函数和 运行 它在 main.js 中传递两个参数:

let myFunction = require('./command-file/commands.js')
myFunction.func1(2, 2)

这不起作用。我的终端根本没有收到 console.log() 消息。 然而。如果我尝试直接从 index.js 将数据发送到 t1.py 而不是先将数据发送到 command.js 并且不导出脚本,它会工作并且 returns '4'(保持记住我不能这样做,因为应用程序的其余部分是如何工作的,但这与这个问题无关,我必须使用 command.js)。我的理论是,出于某种原因 child_process 确实与 module.exports 一起工作,但我不知道为什么...

结构:

.
├── index.js
└── script.py

index.js:

const { spawn } = require('child_process');

const command = spawn('python', ["./script.py", 1, 2]);

let result = '';

command.stdout.on('data', function (data) {
  result += data.toString();
});
command.on('close', function (code) {
  console.log("RESULT: ", result);
});

script.py:

import sys

a = 0
b = 0

try:
  a = sys.argv[1]
  b = sys.argv[2]
except:
  print("DATA_MISSING")

sys.stdout.write("{}".format(int(a) + int(b)))

从节点开始代码index.js