我正在制作一个 node.js 应用程序,我需要将数据发送到一个 python 脚本,它会在其中执行一些计算。command.js然后我需要将数据从 python 脚本返回到我从主脚本运行的discord.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 sysa = 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))});然后我将生成的数据从发送command.js到index.js使用module.exports:module.exports = { 'func1': func1}最后,我require从脚本中导出函数并在传入两个参数时command.js运行它:main.jslet myFunction = require('./command-file/commands.js')myFunction.func1(2, 2)这是行不通的。我的终端根本没有收到任何 console.log() 消息。然而。t1.py如果我尝试直接从发送数据index.js而不首先发送数据command.js并且不导出脚本,它会工作并返回“4”(请记住我不能这样做,因为应用程序的其余部分是如何工作的,但是这与这个问题无关,我必须使用command.js)。我的理论是,出于某种原因,child_processdoesent 工作module.exports,但我不知道为什么......
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
结构:
.
├── index.js
└── script.py
索引.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)))
用node开始代码index.js
添加回答
举报
0/150
提交
取消
