翻翻過去那場(chǎng)雪
2023-02-22 15:28:46
我正在制作一個(gè) node.js 應(yīng)用程序,我需要將數(shù)據(jù)發(fā)送到一個(gè) python 腳本,它會(huì)在其中執(zhí)行一些計(jì)算。command.js然后我需要將數(shù)據(jù)從 python 腳本返回到我從主腳本運(yùn)行的discord.js 命令腳本index.js。我發(fā)送需要用模塊計(jì)算的數(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,我像這樣檢索它并嘗試記錄它(問題是當(dāng)我運(yùn)行主腳本時(shí)它沒有記錄任何內(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從腳本中導(dǎo)出函數(shù)并在傳入兩個(gè)參數(shù)時(shí)command.js運(yùn)行它: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并且不導(dǎo)出腳本,它會(huì)工作并返回“4”(請(qǐng)記住我不能這樣做,因?yàn)閼?yīng)用程序的其余部分是如何工作的,但是這與這個(gè)問題無關(guān),我必須使用command.js)。我的理論是,出于某種原因,child_processdoesent 工作module.exports,但我不知道為什么......
1 回答

四季花海
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
結(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
添加回答
舉報(bào)
0/150
提交
取消