简体   繁体   English

根据命令行参数调用python函数

[英]Call python function based on command line argument

I have a script with several functions: 我有一个具有以下功能的脚本:

def a():
   pass

def b():
   pass 

def c():
   pass

Which by design will be invoked depending on cmd line argument. 在设计上将根据cmd行参数调用哪个方法。 I can create several if statements which will evaluate which function should run: 我可以创建几个if语句来评估应该运行哪个函数:

if args.function == "a":
    a()

elif args.function == "b":
    b()
elif args.function == "c":
    c()

But is there a better way to do this? 但是有更好的方法吗?

You could make a dictionary like so 你可以像这样制作字典

d = {"a" : a,
     "b" : b}

and then dispatch 然后派遣

d[args.function]()

Perhaps you are looking for a library like click ? 也许您正在寻找诸如click类的图书馆? It lets you easily add command-line subcommands with a decorator. 它使您可以轻松地使用装饰器添加命令行子命令。

import click

@click.group()
def cli():
    pass

@cli.command()
def a():
   print("I am a")

@cli.command()
def b():
   print("Je suis b")

if __name__ == '__main__':
    cli()

Sample output: 样本输出:

bash$ ./ick.py --help
Usage: ick.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  a
  b

bash$ ./ick.py a
I am a

Try using eval 尝试使用eval
eval(function_name_passed_as_argument + "()")

def a():
   pass

def b():
   pass 
eval(args.function + "()")  

This doesn't require the use of if-else logic. 这不需要使用if-else逻辑。 Function name passed as argument will be executed directly. 作为参数传递的函数名称将直接执行。

You make a dictionary as already pointed out, but how are you going to handle a bad input? 正如您已经指出的那样,您制作字典,但是您将如何处理错误的输入呢? I would create a default method and use the dict.get method: 我将创建一个默认方法并使用dict.get方法:

def fallback():
    print('That command does not exist')
    # add any code you want to be run for
    # a bad input here...

functions = {
    'a': a,
    'b': b
}

Then call the function by retrieving it: 然后通过检索它来调用该函数:

functions.get(args.function.lower(), fallback)()

Python has several built-in functions that we can utilize for instance Argparse , this method pretty common in python for command line programmable application. Python有几个内置函数可供我们使用,例如Argparse ,此方法在python中非常普遍,适用于命令行可编程应用程序。 The basics: 基础:

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

By this method, you can have something like this: 通过这种方法,您可以得到以下内容:

$ python3 prog.py -v
verbosity turned on
$ python3 prog.py --help
usage: prog.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM