[英]How to run a Python script in Node.js synchronously?
我通过python-shell在 Node.js 中运行以下 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
然后执行以下代码? 任何帮助将不胜感激...这是紧急情况,请!
由于这是异步的,添加一个结束回调(在文档中找到)而不是顶层的指令
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
console.log ("Now reading data");
});
我遇到了同样的问题,并通过在其中使用PythonShell.run
方法做出承诺来解决它。 然后,您只需等待该承诺,您的代码就会同步运行。
承诺方法:
RunPythonScript: function(scriptPath, args, pythonFile){
let options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: [],
scriptPath: scriptPath,
args: args,
};
return new Promise((resolve,reject) =>{
try{
PythonShell.run(pythonFile, options, function(err, results) {
if (err) {console.log(err);}
// results is an array consisting of messages collected during execution
console.log('results', results);
resolve();
});
}
catch{
console.log('error running python code')
reject();
}
})
},
然后,您等待承诺:
await RunPythonScript(YOURscriptPath,YOURargsScript,YOURpythonFile);
它对我有用:
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()
export default { data () { return { } }, method: { callfunction () { console.log ("Now reading data"); }, pyth (){ var PythonShell = require('python-shell'); var vm = this; //save the object (this) in variable vm to use inside pythonshell.run PythonShell.run('sensor.py', function (err) { if (err) throw err; console.log('finished'); vm.callfunction(); }); } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.