如何将python 3.6配置文件转换为argparser代码
我有一个文件.conf,我用ConfigParser()加载到python中。conf文件具有通常的格式(也使用opencv): conf文件很大。我想要一种为ArgumentParser()自动生成python代码的方法,这样我就可以单独编写conf文件,生成一些代码,并删除我不需要的代码:如何将python 3.6配置文件转换为argparser代码,python,configparser,Python,Configparser,我有一个文件.conf,我用ConfigParser()加载到python中。conf文件具有通常的格式(也使用opencv): conf文件很大。我想要一种为ArgumentParser()自动生成python代码的方法,这样我就可以单独编写conf文件,生成一些代码,并删除我不需要的代码: parser = argparse.ArgumentParser() parser.add_argument("-c","--config", help="full pathname to config
parser = argparse.ArgumentParser()
parser.add_argument("-c","--config", help="full pathname to config file", type=str)
# etc.
我没有找到这样的实用程序,但在python中只使用了几个月。虽然我不是绝对肯定,但我会做以下两件事之一
- 创建一个函数,该函数接受
对象,并将其转换为ConfigParser
的等效对象Argparse
- 修正工具
- 正常运行
- 运行神奇的部分,将现在解析的ConfigParser对象作为Argparse命令的大字符串转储到一个新文件中以供查看
- 为它编写正则表达式并进行直接转换
- 写新剧本
- 传入配置的路径
- 运行神奇的部分,将现在解析的ConfigParser对象作为Argparse命令的大字符串转储到一个新文件中以供查看
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))
这两种方法都不是很好的解决方案,但我希望90%的工作都能轻松完成,留下好的日志记录和您自己来查找和转换剩下的几个古怪命令
一旦您对输出感到满意,就可以去掉转储逻辑,直接用它们填充argparse参数
for command in commands:
argparse.add_argument(**command)
我想结账。那座图书馆可供阅读
命令行参数、配置文件、硬编码默认值以及在某些情况下环境变量的组合
这看起来很有希望,会给它一个回顾。是的,我意识到配置是用dict表示的,因此在给定部分是静态的情况下,或者使用re进行搜索时,很容易遍历。我还看到,我可以使用json作为配置文件格式,这也很容易处理。
for command in commands:
argparse.add_argument(**command)