对于所有的能力和选项,argparse
我认为你永远不会得到一个看起来像你想要的“罐装”使用字符串。
也就是说,自从你的原始帖子以来,你有没有看过子解析器?
这是一个准系统实现:
import argparse
parser = argparse.ArgumentParser(prog='mydaemon')
sp = parser.add_subparsers()
sp_start = sp.add_parser('start', help='Starts %(prog)s daemon')
sp_stop = sp.add_parser('stop', help='Stops %(prog)s daemon')
sp_restart = sp.add_parser('restart', help='Restarts %(prog)s daemon')
parser.parse_args()
使用该-h
选项运行它会产生:
usage: mydaemon [-h] {start,stop,restart} ...
positional arguments:
{start,stop,restart}
start Starts mydaemon daemon
stop Stops mydaemon daemon
restart Restarts mydaemon daemon
这种方法的好处之一是能够使用set_defaults
每个子解析器将函数直接连接到参数。我还为stop
and添加了一个“优雅”的选项restart
:
import argparse
def my_stop(args):
if args.gracefully:
print "Let's try to stop..."
else:
print 'Stop, now!'
parser = argparse.ArgumentParser(prog='mydaemon')
graceful = argparse.ArgumentParser(add_help=False)
graceful.add_argument('-g', '--gracefully', action='store_true', help='tries to terminate the process gracefully')
sp = parser.add_subparsers()
sp_start = sp.add_parser('start', help='Starts %(prog)s daemon')
sp_stop = sp.add_parser('stop', parents=[graceful],
description='Stops the daemon if it is currently running.',
help='Stops %(prog)s daemon')
sp_restart = sp.add_parser('restart', parents=[graceful], help='Restarts %(prog)s daemon')
# Hook subparsers up to functions
sp_stop.set_defaults(func=my_stop)
# Uncomment when my_start() and
# my_restart() are implemented
#
# sp_start.set_defaults(func=my_start)
# sp_restart.set_defaults(func=my_restart)
args = parser.parse_args()
args.func(args)
显示“帮助”消息stop
:
$ python mydaemon.py stop -h
usage: mydaemon stop [-h] [-g]
Stops the daemon if it is currently running.
optional arguments:
-h, --help show this help message and exit
-g, --gracefully tries to terminate the process gracefully
“优雅地”停止:
$ python mydaemon.py stop -g
Let's try to stop...