Python2.7 argparse only accepts optional arguments (prefixed) in mutually exclusive groups:
parser = argparse.ArgumentParser(prog='mydaemon')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('--start', action='store_true', help='Starts %(prog)s daemon')
action.add_argument('--stop', action='store_true', help='Stops %(prog)s daemon')
action.add_argument('--restart', action='store_true', help='Restarts %(prog)s daemon')
$ mydaemon -h
usage: mydaemon [-h] (--start | --stop | --restart)
optional arguments:
-h, --help show this help message and exit
--start Starts mydaemon daemon
--stop Stops mydaemon daemon
--restart Restarts mydaemon daemon
Is there a way to make argparse arguments behaves like traditional unix daemon control:
(start | stop | restart) and not (--start | --stop | --restart) ?
For all the abilities and options in
argparseI don’t think you’ll ever get a “canned” usage string that looks like what you want.That said, have you looked at sub-parsers since your original post?
Here’s a barebones implementation:
Running this with the
-hoption yields:One of the benefits of this approach is being able to use
set_defaultsfor each sub-parser to hook up a function directly to the argument. I’ve also added a “graceful” option forstopandrestart:Showing the “help” message for
stop:Stopping “gracefully”: