Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable/Remove argument in argparse

Tags:

Is it possible to remove or disable an argument in argparse, such that it does not show in the help? How?

It is easy to add new arguments:

parser = argparse.ArgumentParser() parser.add_argument('--arg1', help='Argument 1') parser.add_argument('--arg2', help='A second one') 

And I know you can override arguments with a new definition by specifying the "resolve" conflict handler:

#In one script that should stand-alone and include arg1:  parser = argparse.ArgumentParser(conflict_handler='resolve') parser.add_argument('--arg1', help='Argument 1') parser.add_argument('--arg2', help='A second one')  #In another script with similar options parser.add_argument('--arg1', help='New number 1') 

But this still includes arg1 in the help message and results of parse_args Is there anything like

#Wishful thinking #In another script with similar options, that shouldn't include arg1 parser.remove_argument('--arg1') 

Or another reasonably easy way to achieve this?

Also: Would the approach be different if the argument was a positional argument?

Note: the problem with removing arg1 after parsing as suggested here is that the argument still shows in the help

like image 572
Bryan P Avatar asked Sep 27 '15 11:09

Bryan P


People also ask

How do you make Argparse argument optional?

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

How do you delete an argument in Python?

The remove() method takes a single element as an argument and removes it from the List. The item parameter is required, and any type (string, number, List) the element you want to remove. The remove() method only removes the given element from the List.

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.

What does Argparse ArgumentParser () do?

>>> parser = argparse. ArgumentParser(description='Process some integers. ') The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.


1 Answers

Is it possible to remove or disable an argument in argparse, such that it does not show in the help?

Set help to argparse.SUPPRESS when you add the argument, like this:

parser.add_argument('--arg1', help=argparse.SUPPRESS) 

This will prevent the argument from showing up in the default help output.

like image 115
Burhan Khalid Avatar answered Sep 21 '22 15:09

Burhan Khalid