Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments that are dependent on other arguments with Argparse

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?

like image 545
user3715648 Avatar asked Dec 10 '14 21:12

user3715648


People also ask

How do you make an argument optional in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does Argparse ArgumentParser () do?

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 .

What does Nargs do in Argparse?

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.


2 Answers

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()) 
like image 99
Saeed Gharedaghi Avatar answered Sep 22 '22 09:09

Saeed Gharedaghi


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') 
like image 24
randomusername Avatar answered Sep 22 '22 09:09

randomusername