8

I was trying to call a python code from my node file.

Here is my node.js Code:

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

and my python part:

import sys

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

In the cmd window, only util.log('readingin') is shown. What's the problem of my code?

0

6 Answers 6

12

There is no problem ...

Here is a slight tweak of your working code (I convert the buffer to string so its human readable)

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

and here is your python

# python_launched_from_nodejs.py
import sys

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

finally here is output of a run

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

Sign up to request clarification or add additional context in comments.

Comments

8

I was also facing the same issue, I found 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);
});

Comments

1

Your python code is not correct:

import sys

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

2 Comments

what do you mean by not test?
@BingGan its name is not test, it's 'data'
0

You could always try something like this:

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

Comments

0

you can check this package on npm- native-python

it provides a very simple and powerful way to run python functions from node might solve your problem and actually uses 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

# 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'}

1 Comment

It looks like you are promoting your own work. Please see the instructions on self-promotion: "you must disclose your affiliation in your post."
0

A more rigorous implementation could also catch raised exceptions and exit codes, as such


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

I would personally rely on exit codes to handle different outcomes from my Python script rather than raising exceptions, as the exceptions will most likely need to be manually parsed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.