python命令行界面变得简单
easycommandline的Python项目详细描述
轻松命令行.py
python命令行界面的解决方案,灵感来自 tj/commander.js
安装
$ pip install easycommandline
选项
选项用.options()方法定义,也用作 选项的文档。下面的示例分析参数和选项 来自sys.argv
# file favcolor.pyfromeasycommandlineimportprogramprogram.version('1.0.1')program.options(('-r','--red'),('-g','--green'),('-b','--blue'),('-w','--white'),)program.parse_argv()ifprogram.red:print('- red')ifprogram.blue:print('- blue')ifprogram.white:print('- white')
$ python favcolor.py -r -w - red - white
胁迫
# file coercion.pyfromeasycommandlineimportprogramdefcollect(value,previous_value):previous_value.append(value)returnprevious_valuedefmake_range(value):components=value.split('..')returnrange(int(components[0]),int(components[1]))defsum(value,previous_value):returnprevious_value+int(value)program.version('1.0.1')program.options(('-r','--recursive'),('-p','--preload','preload enabled'),('-n','--name','username'),('-i','--integer <int>','an integer argument',int),('-f','--float <float>','a float argument',float),('-a','--anotherfloat','another float argument',float),('-c','--collection [example]','collection',collect,[]),('-x','--range A..B','range',make_range),('-s','--sum','the sum of numbers',sum,0),)program.parse_argv()print('recursive : ',program.recursive)print('preload : ',program.preload)print('name : ',program.name)print('integer : ',program.integer)print('float : ',program.float)print('collection : ',program.collection)print('range : ',program.range)print('sum : ',program.sum)
$ python coercion.py -p --name Tracy -i 1000 --range 5..8 -s 1 2 3 4 recursive : None preload : True name : Tracy integer : 1000 float : None collection : [] range : [5, 6, 7] sum : 10
命令
指定
参数需要与< >
参数可与[ ]一起选择,不能指定超过一个
可选参数
# file cmd.pyfromeasycommandlineimportprogramimportosprogram.version('1.0.1')cmd=program.cmd('cd <path>')cmd.options(('-c','--create','create directory if not existed'),)cmd.description('change directory')@cmd.actiondefaction_for_cmd_cd(cmd,path):ifcmd.createandnotos.path.exists(path):os.makedirs(path)cmd=program.cmd('start server <path> [env]')@cmd.actiondefaction_for_cmd_start_server(cmd,path,env):print(path)print(env)program.parse_argv()
$ python cmd.py cd ~/Desktop/abc -c $ python cmd.py start server ~/Desktop/abc production
自动–帮助
$ python coercion.py -h Usage: python coercion.py [options] Options: -h, --help output usage information -V, --version output the version number -r, --recursive -p, --preload preload enabled -n, --name username -i, --integer <int> an integer argument -f, --float <float> a float argument -a, --anotherfloat another float argument -c, --collection [example] collection -x, --range A..B range -s, --sum the sum of numbers