使参数解析变得容易
项目描述
简单的参数
一个旨在简化命令行参数解析的项目。
在 python 中创建命令行解析器的方法有很多:argparse、docopt、click。这些都是不错的选择,但需要进行大量配置,有时您只需要调用一个函数。输入easyargs。定义你想要调用的函数,装饰它,然后让easyargs 处理命令行。这可能最好用一个带有一个必需参数和两个可选参数的示例来说明:
from __future__ import print_function
import easyargs
@easyargs
def main(name, count=1, greeting='Hello'):
"""A simple greeting program"""
for i in range(count):
print('{greeting} {name}!'.format(greeting=greeting, name=name))
if __name__ == '__main__':
main()
在此示例中,检查 main ,将 arg 关键字转换为位置参数,并将 kwarg 关键字转换为可选参数。如果我们使用帮助标志运行上述脚本,可以看到这一点:
$ 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
有几点值得注意。首先,描述取自函数的文档字符串。其次,不需要将 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 类型。然后,如果设置了一个值,它将被强制转换为类型。
main(arg=True):如果默认值为 bool 类型,则 arg 成为标志选项。
main(a=values):如果参数的长度为 1,那么它将创建一个短参数。
子命令
虽然拥有一个简单的函数解析器很棒,但有时您需要一个子解析器。这可以通过在一个类中包装多个函数来创建。让我们通过复制 git 命令的一部分来用另一个示例来演示这一点。同时我们将介绍使用文档字符串来包含每个函数参数的帮助文本的概念。
from __future__ import print_function
import easyargs
@easyargs
class GitClone(object):
"""A git clone"""
def clone(self, src, _dest):
"""
Clone a repository
:param src: The source repository to clone from
:param _dest: The directory to check the source code to
"""
def commit(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
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。