使用Node.js的child_process调用Python脚本

8

我想在我的node文件中调用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')。我的代码有什么问题?
6个回答

12

这里有一点改进您的可用代码(我将缓冲区转换为字符串以使其易于阅读)。

// 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


7

我也遇到了同样的问题,我找到了这个

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

1
您的Python代码不正确:

import sys

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

你说的"not test"是什么意思? - Bing Gan
@BingGan,它的名字不是test,而是"data"。 - MikeZhang

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

0

你可以在npm上检查这个包- native-python

它提供了一种非常简单而强大的方式,从node中运行python函数,可能解决你的问题并且使用spawn。

import { runFunction } from '@guydev/native-python'
const example = async () => {
   const input = [1,[1,2,3],{'foo':'bar'}]
   const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)

   // error will be null if no error occured.
   if (error) {
       console.log('Error: ', error)
   }

   else {
       console.log('Success: ', data)
       // prints data or null if function has no return value
   }
}

Python 模块

# module: file.py

def hello_world(a,b,c):
    print( type(a), a) 
    # <class 'int'>, 1

    print(type(b),b)
    # <class 'list'>, [1,2,3]

    print(type(c),c)
    # <class 'dict'>, {'foo':'bar'}

看起来你在推广自己的作品。请查看有关自我推广的说明:「_您必须在帖子中披露您的从属关系。_」(https://stackoverflow.com/help/promotion) - starball

0
更严格的实施还可以捕获引发的异常和退出代码,如此等等。

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

process.stdout.on('data', (data) => {
    console.log(data.toString('utf8'));
});

process.stderr.on('data', (stacktrace) => {
    console.error(stacktrace.toString('utf8'));

    // possibly parse the stack trace to handle distinct exceptions
});

process.on('exit', (exitCode) => {
    console.log(`Process ended with code (${exitCode})`);
});

我个人会依赖退出代码来处理我的Python脚本的不同结果,而不是引发异常,因为异常很可能需要手动解析。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接