Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse - Custom Action With No Argument?

class StartAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print "Hello"

start.add_argument('-s', '--start', action=StartAction)

I know normally having the action be something like 'store_true' would prevent the requirement of an argument, but is there a way to use a custom action and still not require an argument to be passed?

So what I want is:

python example.py -s

Hello

like image 869
Takkun Avatar asked Jun 12 '12 17:06

Takkun


People also ask

How do you add an optional argument in Argparse?

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

What is action Store_true in Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

What is action in Argparse?

action defines how to handle command-line arguments: store it as a constant, append into a list, store a boolean value etc. There are several built-in actions available, plus it's easy to write a custom one.

How do you make an argument mandatory in Python?

required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .


1 Answers

Try adding nargs=0 to your start.add_argument:

start.add_argument('-s', '--start', action=StartAction, nargs=0)
like image 172
mgilson Avatar answered Sep 20 '22 05:09

mgilson