Call a Python function in a file with command-line argument
<p>I'm trying to pass arguments from Node.js to Python with <code>child_process</code> spawn. I also want to invoke the specific Python function with one of the argument that I specified in the Node.js array.</p>

<p><code>test.js</code></p>

<pre><code>'use strict';

const path = require('path');
const spawn = require('child_process').spawn;

const exec = (file, fnCall, argv1, argv2) =&gt; {
  const py = spawn('python', [path.join(__dirname, file), fnCall, argv1, argv2]);
  py.stdout.on('data', (chunk) =&gt; {
    const textChunk = chunk.toString('utf8'); // buffer to string
    const array = textChunk.split(', ');
    console.log(array);
  });
};
exec('lib/test.py', 'test', 'argument1', 'argument2'.length - 2);  // =&gt; [ 'argument1', '7' ]
exec('lib/test.py', 'test', 'arg3', 'arg4'.length - 2);  // =&gt; [ 'arg3', '2' ]
</code></pre>

<p>The second argument here is <code>test</code>, which should call the <code>test()</code> Python function.</p>

<p><code>lib/test.py</code>:</p>

<pre><code>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()
</code></pre>

<p>If I try to run this Python file without any Node.js from the command line, the execution looks like this:</p>

<p><code>$ python lib/test.py test arg3 2</code></p>

<p>Where <code>test</code>, <code>arg3</code>, and <code>2</code> are just command-line arguments, but <code>test</code> should call the <code>test()</code> function, which will use the <code>arg3</code>, <code>2</code> arguments for <code>print()</code>.</p>

<p>I'd recommend using <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse</a> to parse the command line arguments. Then you can use <a href="https://docs.python.org/3.5/library/functions.html#eval" rel="nofollow">eval</a> to get the actual function from the input.</p>

<pre><code>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()
</code></pre>

python arguments command-line-arguments sys