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

时间:2016-08-02 19:50:54

标签: python node.js

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

bq

我相应的Node.js代码是:

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"

输出是:

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

Node.js无法同步执行我的Python脚本 ,它首先执行finished Now reading data 函数之后的所有代码然后执行PythonShell.run。如何首先执行PythonShell.run然后执行以下代码?任何帮助都将受到赞赏......请紧急!

4 个答案:

答案 0 :(得分:0)

由于这是异步的,因此添加一个结束回调(在文档中找到)而不是顶级指令

// end the input stream and allow the process to exit 
pyshell.end(function (err) {
  if (err) throw err;
  console.log ("Now reading data");
});

答案 1 :(得分:0)

我遇到了同样的问题,并通过其中的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); 

答案 2 :(得分:0)

它对我有用:

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()

答案 3 :(得分:-1)

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();
              });
              
            }
        }
}