【问题标题】:Call a Python function in a file with command-line argument使用命令行参数在文件中调用 Python 函数
【发布时间】:2017-01-08 11:29:51
【问题描述】:

我正在尝试使用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 test arg3 2

其中testarg32 只是命令行参数,但test 应该调用test() 函数,该函数将使用arg32 参数作为@987654336 @。

【问题讨论】:

    标签: python arguments command-line-arguments sys


    【解决方案1】:

    我建议使用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()
    

    【讨论】:

    • 谢谢!完美运行!
    • @Lanti 没问题,很高兴为您提供帮助
    • 如果每个函数需要的参数个数不同怎么办?
    猜你喜欢
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2013-01-13
    • 2018-11-08
    • 2018-11-04
    • 1970-01-01
    • 2015-01-12
    相关资源
    最近更新 更多