Search code examples
pythonnode.jschild-process

Use node exec to access a function in a python file


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


Solution

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