Arguments that are dependent on other arguments with Argparse

梦想的初衷 提交于 2019-11-29 07:34:20

问题


I want to accomplish something like this:

-LoadFiles
    -SourceFile "" -DestPath ""
    -SourceFolder "" -DestPath ""
-GenericOperation
    -SpecificOperation -Arga "" -Argb ""
    -OtherOperation -Argc "" -Argb "" -Argc ""

A user should be able to run things like:

-LoadFiles -SourceFile "somePath" -DestPath "somePath"

or

-LoadFiles -SourceFolder "somePath" -DestPath "somePath"

Basically, if you have -LoadFiles, you are required to have either -SourceFile or -SourceFolder after. If you have -SourceFile, you are required to have -DestPath, etc.

Is this chain of required arguments for other arguments possible? If not, can I at least do something like, if you have -SourceFile, you MUST have -DestPath?


回答1:


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')



回答2:


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())



回答3:


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.




回答4:


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!"


来源:https://stackoverflow.com/questions/27411268/arguments-that-are-dependent-on-other-arguments-with-argparse

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