我试图找到一种方法在命令行中添加方法名称作为参数。我在 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的新手。
我添加了一个从名称映射到函数对象的字典。该字典还可用于限制解析器接受的选择。
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')
之前的重复
用于getattr
执行模块命名空间的一般搜索以将字符串与函数匹配。这可以在这里使用,但对于初学者来说可能太高级了,甚至对于高级程序员来说也可能太开放了。通常最好将您提供给用户的选择限制在一组已知的有效选项中。
如果这个字典映射令人困惑,我会建议一个更明显的映射
if args.method == 'foo':
foo()
elif args.method == 'bar':
bar()
else:
parser.error('bad method choice')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句