Arguments dependent on other arguments with Argparse

I want to do something like this:

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

The 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 should have either -SourceFile or -SourceFolder after. If you have a -SourceFile, you should have a -DestPath, etc.

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

+6
source share
2 answers

After calling parse_args in the created ArgumentParser instance, it will provide you with a Namespace object. Just make sure that if one of the arguments is present, the other should be there. How:

 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') 
+5
source

Here is an example which, if you specify --makeDependency, forces you to specify -dependency with a value.

This is not only done with argparse, but also with a program that later checks that the user has 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!" 
0
source

Source: https://habr.com/ru/post/979421/


All Articles