Search code examples
javascriptpythonnode.jschild-processsys

Retrieving data from python script using 'child-process' works in normal node.js script, but not in a required script


I am making a node.js application where I need to send data to a python script where it preforms some calculations. Then I need to get the data from the python script back to a discord.js command-script command.js, that I run from the main script index.js. I send the data i need to be calculated with the child_process module:

function func1(arg1, arg2){
    let spawn = require('child_process').spawn
    const pythonProcess = spawn('python',['t1.py', arg1, arg2]);
}

Then I retrieve and process the data in python with the sys module like this:

import sys

a = sys.argv[1]
b = sys.argv[2]

print(int(a) + int(b))
sys.stdout.flush()

After the data is handled in the python script t1.py, I retrieve it like this and try to log it (the problem is that it doesent log anything when I run the main script):

pythonProcess.stdout.on('data', (data) => {
    console.log(Number(data))
});

I then send the resulting data from command.js to index.js using module.exports:

module.exports = {
    'func1': func1
}

Finally I require the function exported from the command.js script and run it in main.js while passing in two arguments:

let myFunction = require('./command-file/commands.js')
myFunction.func1(2, 2)

This does not work. I simply get no console.log() message at all in my terminal. However. If I try to send the data to t1.py directly from index.js without sending the data to command.js first and not exporting the script, it works and returns '4' (Keep in mind I cannot do it this way because of how the rest of the application works, but that is irrelevant to this problem, I have to use command.js). My theory is that for some reason child_process doesent work with module.exports, but I dont know why...


Solution

  • Structure:

    .
    ├── index.js
    └── script.py
    

    index.js:

    const { spawn } = require('child_process');
    
    const command = spawn('python', ["./script.py", 1, 2]);
    
    let result = '';
    
    command.stdout.on('data', function (data) {
      result += data.toString();
    });
    command.on('close', function (code) {
      console.log("RESULT: ", result);
    });
    

    script.py:

    import sys
    
    a = 0
    b = 0
    
    try:
      a = sys.argv[1]
      b = sys.argv[2]
    except:
      print("DATA_MISSING")
    
    sys.stdout.write("{}".format(int(a) + int(b)))
    

    Start the code with node index.js