实现命令行UI的"最干净"方式是什么,类似于git,例如:
git push origin/master git remote add origin git://example.com master
理想情况下还允许更灵活的解析,例如,
jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build
jump_to_folder
是脚本名称,app
是命令,theappname
是"固定位置"参数,"构建"和"v2"等是参数(例如,可能的参数是任何数字/任何前缀为av的数字,或者build/source/TMP /配置)
我可以用一系列if
/ else
/ 手动解析参数elifs
,但必须有更优雅的方法来做到这一点?
作为一个完全理论上的例子,我可以描述UI模式..
app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer
然后通过上面的模式解析提供的参数,并获取一个字典:
>>> print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } }
这样的系统存在吗?如果没有,我将如何沿着这些方向实施某些内容?
argparse是完美的,特别是"子命令"和位置args
import argparse def main(): arger = argparse.ArgumentParser() # Arguments for top-level, e.g "subcmds.py -v" arger.add_argument("-v", "--verbose", action="count", default=0) subparsers = arger.add_subparsers(dest="command") # Make parser for "subcmds.py info ..." info_parser = subparsers.add_parser("info") info_parser.add_argument("-m", "--moo", dest="moo") # Make parser for "subcmds.py create ..." create_parser = subparsers.add_parser("create") create_parser.add_argument("name") create_parser.add_argument("additional", nargs="*") # Parse opts = arger.parse_args() # Print option object for debug print opts if opts.command == "info": print "Info command" print "--moo was %s" % opts.moo elif opts.command == "create": print "Creating %s" % opts.name print "Additional: %s" % opts.additional else: # argparse will error on unexpected commands, but # in case we mistype one of the elif statements... raise ValueError("Unhandled command %s" % opts.command) if __name__ == '__main__': main()
这可以这样使用:
$ python subcmds.py create myapp v1 blah Namespace(additional=['v1', 'blah'], command='create', name='myapp', verbose=0) Creating myapp Additional: ['v1', 'blah'] $ python subcmds.py info --moo usage: subcmds.py info [-h] [-m MOO] subcmds.py info: error: argument -m/--moo: expected one argument $ python subcmds.py info --moo 1 Namespace(command='info', moo='1', verbose=0) Info command --moo was 1
该cmd
模块可能适用于此.
例:
import cmd class Calc(cmd.Cmd): def do_add(self, arg): print sum(map(int, arg.split())) if __name__ == '__main__': Calc().cmdloop()
运行:
$python calc.py (Cmd) add 4 5 9 (Cmd) help Undocumented commands: ====================== add help (Cmd)
有关详细信息,请参阅Python文档或PyMOTW站点.