在argparse中使用互斥组:如何基于组引导逻辑?

问题描述 投票:0回答:0

我希望根据用户指定的内容为我的脚本和通道逻辑提供互斥的参数。我目前拥有的是这样的:

supported_formats = ['xyz','mol','pdb']

defaults = {'extension':'xyz',
            'dirname':None,
            'name':None}

info = '''Add info here.'''

parser = argparse.ArgumentParser(description=info)
group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group()

group1.add_argument('-i', '--infile', help='Specify a file path to a names_smiles csv.')

group2.add_argument('-s', '--smiles', nargs='+', help='Specify your smiles (multiple possible).')
group2.add_argument('-n', '--name', nargs='+', help='Specify (a) name(s) for your molecule.')

parser.add_argument('-d', '--dirname', default=defaults['dirname'], help='Specify the name of the directory to which the coords files will be written.')
parser.add_argument('-x', '--extension', default=defaults['extension'], help='Specify the file extension for your output coordinates. No dot necessary. Supported formats: %s'%', '.join(supported_formats))

mutually_exclusive = parser.add_mutually_exclusive_group()
mutually_exclusive.add_argument_group(group1)
mutually_exclusive.add_argument_group(group2)

args = parser.parse_args()

如您所见,

group1
group2
参数是互斥的,而最后一个则不是。我想稍后根据这些组来引导执行,类似于:

if args.group1: # do Stuff for csv
    print('Using input file %s as input.'%os.path.basename(args.infile))

elif args.group2:
    print('Using manual input.')

else:
    sys.exit('No input specified.')

问题是 argparse 不是这样工作的。为了实现我想要的功能,我需要像这样单独检查每个组的每个参数:

if args.infile:
    print("Group 1 logic")
elif args.name or args.smiles:
    print("Group 2 logic")
else:
    print("No valid arguments were provided.")

现在这没什么大不了的。但我计划在将来添加很多参数,并且我不想有一个包含 10 个

if
组件的
or
语句。

我试图找出是否有参数组的迭代器,以便我可以做类似的事情:

if any([subarg == True for subarg in args.group2.subargs]):
    print('Run group2 logic')

但是查看文档并

dir(parser)
并没有给我任何类似的信息。

这可能吗?还是我必须为每个组手动添加每个参数?

python command-line-interface argparse
© www.soinside.com 2019 - 2024. All rights reserved.