我会为此使用 argparse:
import argparse
import inspect
class myClass(object):
"""description for program"""
def update(self):
"""update method help"""
print 'update command'
def something(self):
"""something command help"""
print 'something command'
if __name__ == '__main__':
program = myClass()
parser = argparse.ArgumentParser(description=program.__doc__)
subparsers = parser.add_subparsers()
for name, method in inspect.getmembers(program, predicate=inspect.ismethod):
subparser = subparsers.add_parser(name, help=method.__doc__)
subparser.set_defaults(method=method)
args = parser.parse_args()
args.method()
命令行示例:
$ python ~/test/docargparse.py --help
usage: docargparse.py [-h] {something,update} ...
description for program
positional arguments:
{something,update}
something something command help
update update method help
optional arguments:
-h, --help show this help message and exit
$ python ~/test/docargparse.py
usage: docargparse.py [-h] {something,update} ...
docargparse.py: error: too few arguments
$ python ~/test/docargparse.py update
update command
$ python ~/test/docargparse.py something
something command