Arguments that are dependent on other arguments with Argparse

£可爱£侵袭症+ 提交于 2019-11-30 06:44:13

After you call parse_args on the ArgumentParser instance you've created, it'll give you a Namespace object. Simply check that if one of the arguments is present then the other one has to be there too. Like:

args = parser.parse_args()
if ('LoadFiles' in vars(args) and 
    'SourceFolder' not in vars(args) and 
    'SourceFile' not in vars(args)):

    parser.error('The -LoadFiles argument requires the -SourceFolder or -SourceFile')

You can use subparsers in argparse

 import argparse
 parser = argparse.ArgumentParser(prog='PROG')
 parser.add_argument('--foo', required=True, help='foo help')
 subparsers = parser.add_subparsers(help='sub-command help')

 # create the parser for the "bar" command
 parser_a = subparsers.add_parser('bar', help='a help')
 parser_a.add_argument('bar', type=int, help='bar help')
 print(parser.parse_args())

Here is a sample that in case you specify --makeDependency, forces you to specify --dependency with a value as well.

This is not done by argparse alone, but also by by the program that later on validates what the user specified.

#!/usr/bin/env python
import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument('--makeDependency', help='create dependency on --dependency', action='store_true')
parser.add_argument('--dependency', help='dependency example')

args = parser.parse_args()

if args.makeDependency and not args.dependency:
    print "error on dependency"
    sys.exit(1)

print "ok!"

There are some argparse alternatives which you can easily manage cases like what you mentioned. packages like: click or docopt.

If we want to get around the manual implementation of chain arguments in argparse, check out the Commands and Groups in click for instance.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!