python - 使用命令行参数在文件中调用 Python 函数

标签 python arguments command-line-arguments sys

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

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

最佳答案

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

相关文章:

mysql - 在 ruby​​ 中连接到 mysql 会产生错误数量的参数错误(4 个,共 0 个)- 如何调试?

c++ - "trick"一个函数在 C++ 中需要多个参数时是否可以接受一个参数?

python - findall 对字符串的问题(预期的字符串或类似字节的对象)

python - 如何修复我的合并排序,因为它会将我的数组还原为未排序的数组?

python - 训练Dialogflow疑惑

java - 使用 Argparse4j 的命令行参数设置标志

Python sys.argv 和 argparse

python - 尝试使用之前训练的 tf.keras 模型作为预训练,但得到“ValueError : Input 0 of layer dense_3 is incompatible with the laye

ruby - 阵列半展平

java - 如何将参数列表传递给VM命令行