我正在制作一個 node.js 應用程序,我需要將數(shù)據(jù)發(fā)送到一個 python 腳本,它會在其中執(zhí)行一些計算。command.js然后我需要將數(shù)據(jù)從 python 腳本返回到我從主腳本運行的discord.js 命令腳本index.js。我發(fā)送需要用模塊計算的數(shù)據(jù)child_process:function func1(arg1, arg2){ let spawn = require('child_process').spawn const pythonProcess = spawn('python',['t1.py', arg1, arg2]);}sys然后我使用這樣的模塊在 python 中檢索和處理數(shù)據(jù):import sysa = sys.argv[1]b = sys.argv[2]print(int(a) + int(b))sys.stdout.flush()在 python 腳本中處理數(shù)據(jù)后t1.py,我像這樣檢索它并嘗試記錄它(問題是當我運行主腳本時它沒有記錄任何內(nèi)容):pythonProcess.stdout.on('data', (data) => { console.log(Number(data))});然后我將生成的數(shù)據(jù)從發(fā)送command.js到index.js使用module.exports:module.exports = { 'func1': func1}最后,我require從腳本中導出函數(shù)并在傳入兩個參數(shù)時command.js運行它:main.jslet myFunction = require('./command-file/commands.js')myFunction.func1(2, 2)這是行不通的。我的終端根本沒有收到任何 console.log() 消息。然而。t1.py如果我嘗試直接從發(fā)送數(shù)據(jù)index.js而不首先發(fā)送數(shù)據(jù)command.js并且不導出腳本,它會工作并返回“4”(請記住我不能這樣做,因為應用程序的其余部分是如何工作的,但是這與這個問題無關,我必須使用command.js)。我的理論是,出于某種原因,child_processdoesent 工作module.exports,但我不知道為什么......
1 回答

四季花海
TA貢獻1811條經(jīng)驗 獲得超5個贊
結(jié)構(gòu):
.
├── 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
提交
取消