简化参数解析
easyargs的Python项目详细描述
简易车
一个旨在使命令行参数解析变得容易的项目。
在python中创建命令行解析器有很多方法:argparse、docopt, 点击。这些都是不错的选择,但是需要很多配置 有时你只需要调用一个函数。输入easyargs。定义 要调用的函数,对其进行修饰并让easyargs完成 命令行。最好用一个 必需参数和两个可选参数:
from__future__importprint_functionimporteasyargs@easyargsdefmain(name,count=1,greeting='Hello'):"""A simple greeting program"""foriinrange(count):print('{greeting} {name}!'.format(greeting=greeting,name=name))if__name__=='__main__':main()
在本例中,main被检查,arg关键字被转换为 位置参数和夸格关键字将被转换 变成可选参数。如果我们使用 帮助标志:
$ python simple.py -h usage: simple_test.py [-h] [--count COUNT] [--greeting GREETING] name A simple greeting program positional arguments: name optional arguments: -h, --help show this help message and exit --count COUNT --greeting GREETING
一些值得注意的事情。首先,描述取自docstring 函数的。其次,不需要将count转换为整数。 因为默认参数是int类型,所以该值被强制为整数:
$ python simple.py World Hello World $ python simple.py everybody --count 2 --greeting Hola Hola everybody! Hola everybody!
如何定义函数
easyargs的目标是避免复杂的配置参数, 但是,让函数指定一些内容,下面的规则列表可能 有用:
- main(arg):arg是必需的位置参数
- main(_arg):arg是可选的位置参数
- main(arg=int, _arg=int):将默认值设置为基本类型将保持 参数的位置,但将其强制为该类型 仅使用int/float进行测试
- main(arg=list):将默认参数设置为列表将使用多个 命令行中的参数。没有道理 不止一次提供这个。
- main(arg=value):创建默认值为value的可选参数
- main(arg=3):如果默认值是int/float类型。如果一个值是 set它将被强制为类型。
- main(arg=True):如果默认值是bool类型,那么arg将成为一个标志 选择。
- main(a=values):如果参数的长度为1,则它将创建一个短 争论。
子命令
虽然有一个简单的函数解析器很好,但有时您需要 子分析器。这可以通过在类中包装多个函数来创建。 让我们通过复制git的一部分来用另一个例子来演示这一点 命令。同时我们将介绍使用docstring的概念 包含每个函数参数的帮助文本。
from__future__importprint_functionimporteasyargs@easyargsclassGitClone(object):"""A git clone"""defclone(self,src,_dest):""" Clone a repository :param src: The source repository to clone from :param _dest: The directory to check the source code to """defcommit(self,a=False,m=None,amend=False):""" Commit a change to the index :param a: Add all tracked files to the index :param m: Supply the commit message on the command line :param amend: Amend the previous commit """print('Committing {m}'.format(m=m))if__name__=='__main__':GitClone()
让我们在命令行上看看这是什么样子:
$ python examples/git_clone.py -h usage: git_clone.py [-h] {clone,commit} ... A git clone positional arguments: {clone,commit} sub-command help clone Clone a repository commit Commit a change to the index optional arguments: -h, --help show this help message and exit $ python examples/git_clone.py clone usage: git_clone.py clone [-h] src [dest] git_clone.py clone: error: too few arguments $ python examples/git_clone.py clone -h usage: git_clone.py clone [-h] src [dest] positional arguments: src The source repository to clone from dest The directory to check the source code to optional arguments: -h, --help show this help message and exit $ python examples/git_clone.py commit -am "Message" Committing Message