如何将模块/方法名称作为命令行参数python 2.7.10传递

时间:2017-08-14 05:35:12

标签: python python-2.7 argparse

我试图找到一种方法在命令行中添加方法名作为参数。我在python 2.7.10中使用argparse模块。

def create_parser():
    parser = argparse.ArgumentParser(description='add method name')
    parser.add_argument('--method_name', help='pass method name to be used')
return parser

def foo():
    return "I am here."

def bar():
    return "I am not here."

def where_are_you(method_name):
    return method_name()

def main():
    return where_are_you(args.method_name)

if __name__ == '__main__':
    main()

我试图通过命令行调用其中一个方法并收到此错误:      " TypeError:' str'对象不可调用。" 请指导我这里我是python的新手。

1 个答案:

答案 0 :(得分:1)

我添加了一个从名称到功能对象的字典。此字典还可用于限制解析器接受的选择。

import argparse
def create_parser():
    parser = argparse.ArgumentParser(description='add method name')
    parser.add_argument('--method_name', help='pass method name to be used', 
          choices=adict)
    return parser

def foo():
    return "I am here."

def bar():
    return "I am not here."

adict = {'foo': foo, 'bar': bar}  # map names to functions

def where_are_you(method_name):
    fn = adict[method_name]
    # could also use getattr
    return fn()

def main():
    args = create_parser().parse_args()     # get the string
    print(args.method_name)                 # debugging
    return where_are_you(args.method_name)

if __name__ == '__main__':
    print(main())          # show the return

测试:

0001:~/mypy$ python stack45667979.py -h
usage: stack45667979.py [-h] [--method_name {foo,bar}]

add method name

optional arguments:
  -h, --help            show this help message and exit
  --method_name {foo,bar}
                        pass method name to be used
0001:~/mypy$ python stack45667979.py --method_name foo
foo
I am here.
0002:~/mypy$ python stack45667979.py --method_name baz
usage: stack45667979.py [-h] [--method_name {foo,bar}]
stack45667979.py: error: argument --method_name: invalid choice: 'baz' (choose from 'foo', 'bar')

之前的重复

Calling a function of a module from a string with the function's name

使用getattr执行模块命名空间的常规搜索,以使字符串与函数匹配。这可以在这里使用,但对初学者来说可能太高级了,即使对于高级程序员来说也许太开放了。通常最好将用户的选择限制为已知有效的一组。

如果这个字典映射令人困惑,我建议一个更明显的映射

if args.method == 'foo':
    foo()
elif args.method == 'bar':
    bar()
else:
    parser.error('bad method choice')
相关问题