簡體   English   中英

使用 argparse 從 CLI 讀取 TOML 配置文件

[英]reading a TOML config file from CLI with argparse

我在編寫支持讀取由 toml 包的配置文件組成的文件路徑的 add 參數時遇到了一些麻煩。 我需要寫的是一個簡單的 CLI 命令,其中配置文件可以指定為 CLI 的一個選項: m2mtest --config <file_path> -

這部分我認為是:

    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) 會這樣做並將其保存到字典中。

非常感謝

你有沒有打電話給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)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM