我正在尝试使用 child_process
spawn 将参数从 Node.js 传递到 Python。我还想使用我在 Node.js 数组中指定的参数之一调用特定的 Python 函数。
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' ]
这里的第二个参数是 test
,它应该调用 test()
Python 函数。
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()
如果我尝试在没有任何 Node.js 的情况下从命令行运行这个 Python 文件,执行过程如下所示:
$ python lib/test.py 测试 arg3 2
其中 test
、arg3
和 2
只是命令行参数,但是 test
应该调用test()
函数,它将为 print()
使用 arg3
、2
参数。
最佳答案
我建议使用 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()
关于python - 使用命令行参数在文件中调用 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256977/