如何解决使用argparse从CLI读取TOML配置文件
编写一个支持读取包含toml软件包的配置文件的文件路径的add参数时,我有些麻烦。
我需要编写的是对CLI的简单命令,其中
可以将配置文件指定为CLI的一个选项:m2mtest --config
我认为这部分是:
parser.add_argument('--config',type=argparse.FileType('r'),help='A configuration file for the CLI',default = [ f for f in os.listdir( '.' )
if os.path.isfile( f ) and f == "m2mtest_config.toml"],dest = 'config' )
if parser.config is not None:
dict = toml.load(parser.config,_dict=dict)
我不确定我写的是否正确..我需要做的是:
如果未指定--config选项,请在当前目录中查找名为m2mtest_config.toml的文件;如果存在这样的文件,请使用它。
如果不存在这样的文件,则说明该CLI运行不使用配置文件---要使用的选项是命令行中指定的选项。
如果在命令行和配置文件中都指定了选项,则命令行值将覆盖配置文件值
我真的很想获得实施该线的帮助。 我知道我不需要解析toml配置文件的文件,因为toml.load(f,_dict = dict)会执行该操作并将其保存到dict中。
非常感谢您
解决方法
你给parser.parse_args()
打电话了吗?另外,不确定您示例中的最后一行。我认为 dict
是一个保留字,而不是一个有效的变量。另外,不确定您是否需要 loads
(不是 load
)的第二个参数。无论如何,这对我有用:
import argparse
import os
import toml
parser = argparse.ArgumentParser()
parser.add_argument(
'--config',type=argparse.FileType('r'),help='A configuration file for the CLI',default = [
f for f in os.listdir( '.' )
if os.path.isfile( f ) and f == "m2mtest_config.toml"
],dest = 'config'
)
args = parser.parse_args()
toml_config = toml.loads(parser.config) if args.config else {}
# merge command line config over config file
config = {**toml_config,**vars(args)}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。