Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the text "optional arguments" in argparse

For some reason I do not use positional arguments in my program but accept "optional" arguments only, controlling whether an argument is truly optional by facilities like narg='?' or action='store_true'. Thus the "optional arguments" in the help text will be misleading. Can I display it simply as "arguments"? Thank you.

like image 375
ziyuang Avatar asked Jun 07 '13 09:06

ziyuang


People also ask

How do you make Argparse argument optional?

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

How do you specify optional named parameters in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

What are positional and optional arguments in Argparse?

Python argparse optional argument These are optional arguments. The module is imported. An argument is added with add_argument . The action set to store_true will store the argument as True , if present.

What is parse_args () in Python?

parse_args will take the arguments you provide on the command line when you run your program and interpret them according to the arguments you have added to your ArgumentParser object.


2 Answers

import argparse

parser = argparse.ArgumentParser()
for grp in parser._action_groups:
    if grp.title == 'optional arguments':
        grp.title = 'arguments'
...
like image 196
falsetru Avatar answered Oct 04 '22 02:10

falsetru


Well, looking at the argparse source it seems to me that it's as simple as overwriting the title of parser._optionals, like this:

parser._optionals.title = "my mandatory arguments, they are actually optionals, but I'll check for their presence"

Probably I should mention that it's a dirty hack, and your whole idea is a bit insane, since switching to positional arguments is so easy to do, and optional arguments are optional.

like image 44
kirelagin Avatar answered Oct 04 '22 02:10

kirelagin