使用node.js child_process调用python脚本

时间:2015-12-10 23:46:53

标签: javascript python node.js

我试图从我的节点文件中调用python代码。

这是我的node.js代码:

var util = require("util");

var spawn = require("child_process").spawn;
var process = spawn('python',["workpad.py"]);

util.log('readingin')

process.stdout.on('data',function(data){
    util.log(data);
});

和我的python部分:

import sys

data = "test"
print(data)
sys.stdout.flush()

在cmd窗口中,仅显示util.log('readingin')。我的代码有什么问题?

4 个答案:

答案 0 :(得分:3)

没有问题......

这是对您的工作代码的轻微调整(我将缓冲区转换为字符串,因此其人类可读)

// spawn_python.js
var util = require("util");

var spawn = require("child_process").spawn;
var process = spawn('python',["python_launched_from_nodejs.py"]);

util.log('readingin')

process.stdout.on('data',function(chunk){

    var textChunk = chunk.toString('utf8');// buffer to string

    util.log(textChunk);
});

这是你的python

# python_launched_from_nodejs.py
import sys

data = "this began life in python"
print(data)
sys.stdout.flush()

最后这里是一个运行

的输出
node spawn_python.js 
11 Dec 00:06:17 - readingin
11 Dec 00:06:17 - this began life in python

node --version

V5.2.0

答案 1 :(得分:1)

您的python代码不正确:

import sys

data = "test"
print(data)   ###not test
sys.stdout.flush()

答案 2 :(得分:1)

我也遇到了同样的问题,我发现this

var myPythonScript = "script.py";
// Provide the path of the python executable, if python is available as 
// environment variable then you can use only "python"
var pythonExecutable = "python.exe";

// Function to convert an Uint8Array to a string
var uint8arrayToString = function(data){
    return String.fromCharCode.apply(null, data);
};

const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);

// Handle normal output
scriptExecution.stdout.on('data', (data) => {
   console.log(uint8arrayToString(data));
});

// Handle error output
scriptExecution.stderr.on('data', (data) => {
    // As said before, convert the Uint8Array to a readable string.
    console.log(uint8arrayToString(data));
});

scriptExecution.on('exit', (code) => {
    console.log("Process quit with code : " + code);
});

答案 3 :(得分:0)

你可以尝试这样的事情:

var child_process = require('child_process');

  child_process.exec('python myPythonScript.py', function (err){
    if (err) {
    console.log("child processes failed with error code: " + err.code);
  }
});