1

I am new to node's child_process and I am trying to execute python and get its results back to node

I want to use exec, not to execute a simple command but to access a python file and execute it

Say my python.py is

try :
    import anotherPythonFile
    print('hello2')
    # anotherPythonFile.names().getNames()  
except Exception as e :
    print(e)

I try to test this and have hello2 returned ,but I get nothing

exec('D:\prjt\test\python.py', (er, stdout, stderr)=>{
  console.log('exec test', stdout);      
}) 

If this worked I would uncomment and execute anotherPythonFile.names().getNames()

What is the error here?

Also, can I access the anotherPythonFile directly and somehow set the function I want to execute ? I want to do (example)

exec('D:\prjt\test\anotherPythonFile.py.names().getNames()', (er, stdout, stderr)=>{
  console.log('exec test', stdout);      
}) 

Is this possible?

Thank you

1 Answer 1

2

Here's an example of running a Python script from Node.js and reading its output:

hello.py

print("Hello from Python!")

main.js

const { spawn } = require('child_process');

const py = spawn('python3', ['/home/telmo/hello.py'])

py.stdout.on('data', (data) => {
  console.log(`${data}`)
});

Running node main.js returns:

Hello from Python!

Alternatives

You can also use execFile instead of spawn:

const { execFile } = require('child_process');

const py = execFile('python3', ['/home/telmo/hello.py'], (error, stdout, stderr) => {
  if (error || stderr) {
    // Handle error.
  } else {
    console.log(stdout)
  }
})

Or exec:

const { exec } = require('child_process');

const py = exec('python3 /home/telmo/hello.py', (error, stdout, stderr) => {
  if (error || stderr) {
    // Handle error.
  } else {
    console.log(stdout)
  }
})
Sign up to request clarification or add additional context in comments.

5 Comments

Hi there. Yes, I also know about spawn, is very flexible, but I am experimenting with exec and I was wondering if I could use exec for python files. There is a big python+node project coming up and I want to research all the options first. So exec is not a choice for python files, only spawn ? Thank you
@codebot Okay, I wrote two more examples with execFile and exec to give you some options over spawn.
You might want to turn the exec into a promise so you can await for it. Would you like an example of that?
Thanks for the tips. One last thing, is possible to define input arguments and/or a specific function in exec ? Something like exec('python3 /home/telmo/hello.py aPythonFunctionToExecute argumentOne argumentTwo' Thanks
I think you'd have to use execFile or spawn for that. At least that's what it looks like in the docs.

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.