1

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

1 Answer 1

4

I'd recommend using argparse to parse the command line arguments. Then you can use eval to get the actual function from the input.

import argparse

def main():
    # Parse arguments from command line
    parser = argparse.ArgumentParser()

    # Set up required arguments this script
    parser.add_argument('function', type=str, help='function to call')
    parser.add_argument('first_arg', type=str, help='first argument')
    parser.add_argument('second_arg', type=str, help='second argument')

    # Parse the given arguments
    args = parser.parse_args()

    # Get the function based on the command line argument and 
    # call it with the other two command line arguments as 
    # function arguments
    eval(args.function)(args.first_arg, args.second_arg)

def test(first_arg, second_arg):
    print(first_arg)
    print(second_arg)

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You! Works perfectly!
@Lanti No problem, glad to help
What if the number of parameters required for each function is different?

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.