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
?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments. The argparse is a standard module; we do not need to install it. A parser is created with ArgumentParser and a new parameter is added with add_argument .
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
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())
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With