[英]How to convert python 3.6 config file into argparser code
I have a file.conf that I load into python with ConfigParser().我有一个 file.conf,我用 ConfigParser() 加载到 python 中。 The conf file has the usual format (using opencv also): conf 文件具有通常的格式(也使用 opencv):
[decorations]
timestamp_fg= 255,255,255
timestamp_bg= 0,0,0
font_scale = 1.5
The conf file is large. conf文件很大。 I would like a way to automatically generate python code for ArgumentParser() so I can single author the conf file, gen some code, and remove code I don't need:我想要一种为 ArgumentParser() 自动生成 python 代码的方法,这样我就可以单独创作 conf 文件,生成一些代码,并删除我不需要的代码:
parser = argparse.ArgumentParser()
parser.add_argument("-c","--config", help="full pathname to config file", type=str)
# etc.
I didn't find such a utility, but still only been in python for few months.我没有找到这样的实用程序,但仍然只使用python几个月。
While I'm not absolutely certain, I'd do one of two things虽然我不是绝对确定,但我会做两件事之一
Create a function that accepts an ConfigParser
object and converts it into Argparse
's equivalent创建一个接受ConfigParser
对象并将其转换为Argparse
等价物的函数
Write a regex for it and do a direct conversion为它写一个正则表达式并进行直接转换
Simply using string.format()
is probably fine简单地使用string.format()
可能没问题
# make a template for your Argparse options
GENERIC_COMMAND = """\
parser.add_argument(
"--{long_name}", "-{short_name}",
default="{default}",
help="help_text")"""
...
# parse ConfigParser to commands
commands = [
{
"long_name": "argumentA",
},
{
"long_name": "argumentB",
"help_text": "Do Thing B"
},
...
]
commands_to_write_to_file = []
for command in commands:
try:
commands_to_write_to_file.append(
GENERIC_COMMAND.format(**command)) # expand command to args
except Exception as ex:
print("Caught Exception".format(repr(ex)))
# to view your commands, you can write commands to file
# or try your luck with the help command
with open(out.txt, "w") as fh:
fh.write("\n\n".join(commands_to_write_to_file))
Neither of these are great solutions, but I expect will get 90% of the work done easily, leaving good logging and yourself to find and convert the remaining few oddball commands.这些都不是很好的解决方案,但我希望可以轻松完成 90% 的工作,留下良好的日志记录和您自己来查找和转换剩余的几个奇怪的命令。
Once you're happy with the output, you can get rid of your dump logic and fill argparse arguments directly with 'em instead一旦您对输出感到满意,您就可以摆脱转储逻辑并直接用 'em 填充 argparse 参数
for command in commands:
argparse.add_argument(**command)
I would checkout ConfigArgParse .我会检查ConfigArgParse 。 That library allows for该库允许
a combination of command line args, config files, hard-coded defaults, and in some cases, environment variables命令行参数、配置文件、硬编码默认值以及某些情况下环境变量的组合
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.