0

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

1
  • Have edited my answer Commented Jul 7, 2020 at 21:56

1 Answer 1

1

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

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

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.