简单的cli入口点和参数解析。
cliep的Python项目详细描述
cliep python控制台入口点库
cliep(cli entrypoint)是一个小型的、无依赖关系的系统,它通过decorators使用一个主entrypoint函数来简化与tty和控制台的接口,并带有可选的自动参数解析。
安装:
pip3 install cliep
建议对单个项目的依赖项使用virtualenv。 对于更大的项目,您还可以将cliep添加到requirements.txt中。
文档:
cliep
命名空间包含两个重要元素:entrypoint
,和Argument
。
entrypoint:
arg_map - the list of arguments to parse and send to the entrypoint.
help_func - function to handle printing the help page on err/trigger. Uses builtin help generator by default.
help_trigger - The flag to trigger help off of, defaults to '-h'. NOTE: this overrides any arguments that share the same name.
入口点还需要输入提示,提示它们返回int
或None
,否则
入口点将不允许运行。
Argument:
shortname: str - Required, specifies the shorthand command name ('-a', '-b', etc).
longname: str - Optional, allows for a second proper command name ('--append').
is_flag: bool - Specifies whether or not the argument is expecting a value, defaults False.
is_required: bool - Specifies whether or not this argument must be found, defaults False.
default: any - Specifies a default value for optional arguments that are not supplied.
这两个元素构成了cliep希望解决的整个用例。 这允许自动分析参数并将它们输入指定的入口点。
一个重要的注意事项:当使用参数时,每个参数的值都被传递到
入口点的添加顺序。例如,参数a, b, c
将被发送到
入口点为a, b, c
。此外,参数使用入口点的类型暗示
发送前要进行类型转换的参数。因此,自定义参数解析需要类型提示。
例如:
@entrypoint([Argument('-a')])defmain(a:int)->int:returna
只要a
参数被类型提示,这个例子就可以工作。
这种类型暗示的广泛使用是为了消除一个猜谜游戏 是来回传递,并降低可能的失败点。
如果向类型转换参数(例如str
->;int
)提供了错误数据,则
将设置为None
,并转发到入口点。如果失败的论点
强制是必需字段,将向用户显示帮助消息。就是这样
正确的入口点可以处理通知用户错误(或没有)的输入,或者手动设置
默认值。尽管这可能不是最优雅的解决方案,但这允许
需要或需要类型转换时的错误处理。
如果入口点中的类型提示是list
或dict
(或泛型对应项),
由于pythons预处理的并发症,cliep将提高一个NotImplementedError
或argv。
如果要覆盖默认的帮助输出,help_func
应该是:
error: str = Error text in case of missing required field.
args: List[Argument] - The list of argument objects.
trigger: str - The trigger phrase that is used to trigger the help screen.
示例:
在最基本的形式中,入口点如下:
fromcliepimportentrypoint@entrypointdefmain(argv,argc)->int:return0
您可以看到,如果没有自定义参数解析,entrypoint只会将argv和len(argv)转发到entrypoint。 另一个需要注意的重要事情是使用类型暗示。cliep使用类型提示来强制返回tty。 因此,entrypoint函数必须要么类型提示“int”类型的返回,要么类型为“none”。
更复杂的示例如下:
fromcliepimportentrypoint,Argument@entrypoint([Argument('-f','--flag',is_flag=True),Argument('-i','--input',is_required=True),])defmain(flag:bool,user_input:int)->int:print(flag,user_input)returnuser_inputor0
在本例中,我们进一步使用类型暗示,因为列表中的参数是传递的 按它们在列表中的位置以及作为每个 参数被收集,它们使用主函数声明中的类型提示来知道 也要输入cast。因此,在entrypoint函数中,所有参数都必须具有类型 暗示。