I'm trying to pass arguments from Node.js to Python with child_process spawn. I also want to invoke the specific Python function with one of the argument that I specified in the Node.js array.
test.js
'use strict';
const path = require('path');
const spawn = require('child_process').spawn;
const exec = (file, fnCall, argv1, argv2) => {
const py = spawn('python', [path.join(__dirname, file), fnCall, argv1, argv2]);
py.stdout.on('data', (chunk) => {
const textChunk = chunk.toString('utf8'); // buffer to string
const array = textChunk.split(', ');
console.log(array);
});
};
exec('lib/test.py', 'test', 'argument1', 'argument2'.length - 2); // => [ 'argument1', '7' ]
exec('lib/test.py', 'test', 'arg3', 'arg4'.length - 2); // => [ 'arg3', '2' ]
The second argument here is test, which should call the test() Python function.
lib/test.py:
import sys
def test():
first_arg = sys.argv[2]
second_arg = sys.argv[3]
data = first_arg + ", " + second_arg
print(data, end="")
sys.stdout.flush()
If I try to run this Python file without any Node.js from the command line, the execution looks like this:
$ python lib/test.py test arg3 2
Where test, arg3, and 2 are just command-line arguments, but test should call the test() function, which will use the arg3, 2 arguments for print().