我正在尝试做一件非常简单的事情 - 只有两个选项:-p 和 -c,它们互斥并且可能有也可能没有 argument,使用可选参数执行 th...is 或不使用参数执行 th...at。这是我得到的:
def main():
import argparse
parser = argparse.ArgumentParser(description = '''ArgParser with optional argument''',
argument_default = argparse.SUPPRESS)
group1 = parser.add_mutually_exclusive_group(required=True)
group1.add_argument('-p', '--project', dest='proj',
nargs='?', const='all', type=str,
help='list of project(s)')
group1.add_argument('-c', '--component', dest='comp',
nargs='?', const='all', type=str,
help='list of Component(s)')
args = parser.parse_args()
print(args)
if args.proj:
outString = 'project/'+args.proj if args.proj is not 'all' else 'projects'
elif args.comp:
outString = 'component/'+args.comp if args.comp is not 'all' else 'components'
else: pass
print('OutPutString: '+outString)
if __name__ == "__main__":
import sys
try: sys.exit(main())
except KeyboardInterrupt: pass
finally: print
对于 if-elif-else block 中的第一个条件,它工作得很好,所以它工作:
dass@mon105:~$ ./argParseOpts.py -p
Namespace(proj='all')
OutPutString: projects
#
dass@mon105:~$ ./argParseOpts.py -p testing
Namespace(proj='testing')
OutPutString: project/testing
但如果使用 -c 而不是 -p(即第二个条件)则不是:
dass@mon105:~$ ./argParseOpts.py -c
Namespace(comp='all')
Traceback (most recent call last):
File "./argParseOpts.py", line 32, in <module>
try: sys.exit(main())
File "./argParseOpts.py", line 21, in main
if args.proj:
AttributeError: 'Namespace' object has no attribute 'proj'
任何人都可以告诉我是否遗漏了什么或做错了什么吗?如果重要的话,使用 v2.7.2。干杯!
请您参考如下方法:
没有设置任何属性,因为您将 argument_default 值设置为 argparse.SUPPRESS,这意味着永远不会设置属性,除非它们具有明确的值。
Set 可以为每个参数设置一个显式的 default=None 值,以再次获得这些特定选项的属性:
group1.add_argument('-p', '--project', dest='proj',
nargs='?', const='all', type=str,
help='list of project(s)', default=None)
group1.add_argument('-c', '--component', dest='comp',
nargs='?', const='all', type=str,
help='list of Component(s)', default=None)
并且 args.proj 和 args.comp 属性将再次始终设置。 None 是一个假值,因此 if args.proj 测试不会通过移动到另一个分支,例如。
另一种方法是使用 hasattr() 来查看属性是否已设置:
if hasattr(args, 'proj'):
