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()
.
答案 0 :(得分:4)
我建议使用argparse来解析命令行参数。然后,您可以使用eval从输入中获取实际函数。
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()