用于生成匹配的参数分析器和配置文件的函数
argutils的Python项目详细描述
argutils提供一组函数,用于快速生成具有匹配配置文件的命令行程序。特别是,不需要分别构建ArgumentParser和configParser,Argutils允许用户从JSON或YAML文件构建接口,然后使用它来构建参数解析器和匹配的配置文件。
安装
$ pip install argutils
用法示例
假设我们有一个玩具程序,它有三个参数:要打印的消息、打印的次数和打印的位置。我们有两个文件,一个参数规范文件,我们将调用example_spec.yml,还有我们的程序,example.py。
在示例中
在示例中。py: 让我们看看我们有什么: 我们可以看到在yaml文件中指定的所有参数都在这里。让我们编写一个配置文件并检查: 注意,这里没有显示两个参数:output和init。使用yaml文件中的\u exclude标志排除这些数据。这对于不应使用配置文件设置的参数(包括一次性参数)非常有用。 让我们测试一下: 我们可以使用命令行标志或通过修改配置文件中的值来指定参数。命令行中指定的值具有优先权,后跟配置文件值,如果未指定其他值,则重设规范文件默认值。_meta:help:>A program that prints a message some number of times to an outputfilemessage:help:the message to printdefault:"Helloworld!"times:help:how many times to print the messagedefault:3type:intoutput:help:where to write the file_exclude:Truedefault:stdouttype:File-winit:help:write a config file with default values_exclude:Trueargtype:flag
try:importConfigParserexceptImportError:importconfigparserasConfigParserimportargutilsfromargutilsimport(read,export)SPEC_FILE='example_spec.yml'CONF_FILE='example.cfg'defmain():# Used in the config file and argument parser's helpprog_name='example.py'config=ConfigParser.SafeConfigParser()# Read the spec and build a parser from itargsdict=read.from_yaml(open(SPEC_FILE).read())parser=export.to_argparser(prog_name,argsdict)# If the config file exists and we can read it, use it to set the# defaultsifconfig.read(CONF_FILE):parser=argutils.set_parser_defaults(parser,config)args=parser.parse_args()ifargs.init:export.to_config_file(prog_name,argsdict,CONF_FILE)for_inrange(args.times):args.output.write(args.message+'\n')if__name__=='__main__':main()
$ python example.py --help
usage: example.py [-h][--message MESSAGE][--times TIMES][--output OUTPUT][--init]
A program that prints a message some number of times to an output file
optional arguments:
-h, --help show this help message and exit
--message MESSAGE the message to print
--times TIMES how many times to print the message
--output OUTPUT where to write the file
--init write a config file with default values
$ python example.py --init
$ cat example.cfg
## A program that prints a message some number of times to an output file
[example.py]# the message to print
message= Hello world!
# how many times to print the message
times=3
$ python example.py
Hello world!
Hello world!
Hello world!
$ python example.py --times 1
Hello world!