python 3.6的现代声明式参数解析器+
declarative-parser的Python项目详细描述
python 3.6+的现代声明式参数解析器。强有力的 单击,像argparse一样集成,声明性的作为sqlalchemy。麻省理工学院 有执照的。Documented on RTD。安装 使用:
python3 -m pip install declarative_parser
像argparse一样简单
它建立在argparse之上-你已经知道的一切都是有效的!
fromdeclarative_parserimportParser,ArgumentclassMyParser(Parser):square=Argument(help='display a square of a given number')parser=MyParser()args=parser.parse_args()print(args.square**2)
嵌套和并行
大家都知道嵌套参数。平行组呢?
supported_formats=['png','jpeg','gif']classInputOptions(Parser):path=Argument(type=argparse.FileType('rb'),optional=False)format=Argument(default='png',choices=supported_formats)classOutputOptions(Parser):format=Argument(default='jpeg',choices=supported_formats)scale=Argument(type=int,default=100,help='Rescale image to %% of original size')classImageConverter(Parser):description='This app converts images'verbose=Argument(action='store_true')input=InputOptions()output=OutputOptions()parser=ImageConverter()commands='--verbose input image.png output --format gif --scale 50'.split()namespace=parser.parse_args(commands)assertnamespace.input.format=='png'assertnamespace.output.format=='gif'
智能
利用python 3类型提示减少语法分析器的繁琐任务 写两三行字。位置,关键字参数,类型 提示,文档字符串-所有内容都可以有意义地转换为 分析器。如果你决定控制,只要覆盖 自动推导参数,Argument()定义为 类变量。
importargparsefromdeclarative_parserimportArgumentfromdeclarative_parser.constructor_parserimportConstructorParserclassMyProgram:database=Argument(type=argparse.FileType('r'),help='Path to file with the database')def__init__(self,text:str,threshold:float=0.05,database=None):"""My program does XYZ. Arguments: threshold: a floating-point value defining threshold, default 0.05 database: file object to the database if any """print(text,threshold,None)parser=ConstructorParser(MyProgram)options=parser.parse_args()program=parser.constructor(**vars(options))
而且它非常直观地工作:
$ ./my_program.py test --threshold 0.6 test0.6 None $ ./my_program.py test --threshold f usage: my_program.py [-h][--database DATABASE][--threshold THRESHOLD] text {} ... my_program.py: error: argument --threshold: invalid float value: 'f' $ ./my_program.py --threshold 0.6 usage: my_program.py [-h][--database DATABASE][--threshold THRESHOLD] text {} ... my_program.py: error: the following arguments are required: text
支持三种docstring格式:google、numpy和 重构文本,默认为google。
ps.它也可以与函数一起工作;请参阅 FunctionParser。
实用
如果你只想出示你的课程许可证怎么办?还是版本?是 有必要写一个单独的逻辑吗?DeclarativeParser为您提供 实用工具装饰器:@action,它利用了 argparse.Action,留下了其他必要的样板 代码。
__version__=2.0importargparsefromdeclarative_parserimportactionfromdeclarative_parser.constructor_parserimportConstructorParserclassMyProgram:def__init__(self,threshold:float=0.05):"""My program does XYZ. Arguments: threshold: a floating-point value, default 0.05 """pass@actiondefversion(options):print(__version__)parser=ConstructorParser(MyProgram)options=parser.parse_args()program=parser.constructor(**vars(options))
一个动作的执行将(默认情况下)导致程序退出 完成后立即。
请参阅以下运行示例:
$ ./my_program.py --version
2.0
请参阅the documentation中的更多示例。