Takkun Takkun - 6 months ago 24
Python Question

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

Answer

Try adding nargs=0 to your start.add_argument:

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