向命令行公开您的api。
commandline的Python项目详细描述
命令行界面帮助程序
这是一个帮助模块,用于制作直观的命令行程序 零努力。它需要一个函数签名,如:
example_function(string1, string2='something', string3='something else')
并将其转换为一个简单的命令行应用程序,用法如下:
example_program string1 [string2 [string3]]
你所要做的就是:
if __name__ == "__main__": import commandline commandline.run_as_main(example_function)
限制
请注意,它当前无法打印参数以外的帮助信息 它们的默认值,但如果是 任何用途。
参数的帮助可能会附带python3000的函数注释。 http://www.python.org/dev/peps/pep-3107/
参数类型是从默认参数推断出来的。 当前支持的是:int、float、bool、str、commandline.choice
如果没有默认参数,则无法推断类型,因此假设str.
>>> import commandline >>> commandline.TESTMODE=1 >>> def test1(arg1=1, arg2=2, arg3=3): ... print [arg1, arg2, arg3] ... >>> commandline.run_as_main(test1, []) [1, 2, 3] >>> commandline.run_as_main(test1, ['6']) [6, 2, 3] >>> commandline.run_as_main(test1, ['--arg1=6', '--arg2=7', '--arg3=8']) [6, 7, 8] >>> commandline.run_as_main(test1, ['6', '7', '8']) [6, 7, 8]>>> commandline.run_as_main(test1, ['6', '7', '8', '9'], 'test.py') Usage: test.py [arg1 [arg2 [arg3]]] [Options] <BLANKLINE> (Please put options last, and no more args than shown.) Unexpected argument(s): 9>>> commandline.run_as_main(test1, ['--arg1=6', '7', '8'], 'test.py') Usage: test.py [arg1 [arg2 [arg3]]] [Options] <BLANKLINE> (Please put options last, and no more args than shown.) Unexpected argument(s): 7, 8>>> def test2(arg1=1, arg2=2, arg3=3): ... return [arg1, arg2, arg3] ... >>> commandline.run_as_main(test2, ['6', '7', '8']) [6, 7, 8]>>> def nodefault(arg1, arg2, arg3): ... return [arg1, arg2, arg3] >>> # If we have no default arguments, we assume you want strings: >>> commandline.run_as_main(nodefault, ['6', '7', '8']) ['6', '7', '8'] >>> commandline.run_as_main(nodefault, [], 'test.py') Usage: test.py arg1 arg2 arg3 [Options] <BLANKLINE> The following compulsory arguments are missing: arg1, arg2, arg3