gpt4 book ai didi

python - 如何在 Node.js 中同步运行 Python 脚本?

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:00 24 4
gpt4 key购买 nike

我正在 Node.js 中通过 python-shell 运行以下 Python 脚本:

import sys
import time
x=0
completeData = "";
while x<800:
crgb = ""+x;
print crgb
completeData = completeData + crgb + "@";
time.sleep(.0001)
x = x+1
file = open("sensorData.txt", "w")
file.write(completeData)
file.close()
sys.stdout.flush()
else:
print "Device not found\n"

我对应的 Node.js 代码是:

var PythonShell = require('python-shell');

PythonShell.run('sensor.py', function (err) {
if (err) throw err;
console.log('finished');
});
console.log ("Now reading data");

输出是:

Now reading data
finished

但预期输出是:

finished 
Now reading data

Node.js 无法同步执行我的 Python 脚本,它首先执行 PythonShell.run 函数后面的所有代码,然后执行 PythonShell.run.如何先执行 PythonShell.run 然后执行以下代码?任何帮助将不胜感激...这是紧急情况!

最佳答案

它对我有用:

let {PythonShell} = require('python-shell');

var options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: [],
scriptPath: '',
args: []
};

async function runTest()
{
const { success, err = '', results } = await new Promise(
(resolve, reject) =>
{
PythonShell.run('hello.py', options,
function (err, results)
{
if (err)
{
reject({ success: false, err });
}

console.log('PythonShell results: %j', results);

resolve({ success: true, results });
}
);
}
);

console.log("python call ends");

if (! success)
{
console.log("Test Error: " + err);
return;
}

console.log("The result is: " + results);

// My code here

console.log("end runTest()");
}

console.log('start ...');

runTest();

console.log('... end main');

结果是:

start ...
... end main
PythonShell results: ["Hello World!"]
python call ends
The result is: Hello World!
end runTest()

关于python - 如何在 Node.js 中同步运行 Python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com