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
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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 .
Try adding nargs=0
to your start.add_argument
:
start.add_argument('-s', '--start', action=StartAction, nargs=0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With