python - 在 Python 的命令行中允许覆盖配置选项的最佳方法是什么?

标签 python command-line configuration-files

我有一个 Python 应用程序,它需要很多(约 30 个)配置参数。到目前为止,我使用 OptionParser 类在应用程序本身中定义默认值,并可以在调用应用程序时在命令行中更改各个参数。

现在我想使用“正确的”配置文件,例如来自 ConfigParser 类。同时,用户应该仍然可以在命令行中更改个别参数。

我想知道是否有任何方法可以将这两个步骤结合起来,例如使用 optparse(或更新的 argparse)来处理命令行选项,但从 ConfigParse 语法中的配置文件中读取默认值。

任何想法如何以简单的方式做到这一点?我真的不喜欢手动调用 ConfigParse,然后手动将所有选项的所有默认值设置为适当的值...

最佳答案

我刚刚发现您可以使用 argparse.ArgumentParser.parse_known_args() 做到这一点。首先使用 parse_known_args() 从命令行解析配置文件,然后使用 ConfigParser 读取它并设置默认值,然后使用 parse_args() 解析其余选项>。这将允许您拥有一个默认值,用配置文件覆盖它,然后用命令行选项覆盖它。例如:

默认没有用户输入:

$ ./argparse-partial.py
Option is "default"

配置文件中的默认值:

$ cat argparse-partial.config 
[Defaults]
option=Hello world!
$ ./argparse-partial.py -c argparse-partial.config 
Option is "Hello world!"

配置文件中的默认值,被命令行覆盖:

$ ./argparse-partial.py -c argparse-partial.config --option override
Option is "override"

argprase-partial.py 紧随其后。正确处理 -h 寻求帮助有点复杂。

import argparse
import ConfigParser
import sys

def main(argv=None):
    # Do argv default this way, as doing it in the functional
    # declaration sets it at compile time.
    if argv is None:
        argv = sys.argv

    # Parse any conf_file specification
    # We make this parser with add_help=False so that
    # it doesn't parse -h and print help.
    conf_parser = argparse.ArgumentParser(
        description=__doc__, # printed with -h/--help
        # Don't mess with format of description
        formatter_class=argparse.RawDescriptionHelpFormatter,
        # Turn off help, so we print all options in response to -h
        add_help=False
        )
    conf_parser.add_argument("-c", "--conf_file",
                        help="Specify config file", metavar="FILE")
    args, remaining_argv = conf_parser.parse_known_args()

    defaults = { "option":"default" }

    if args.conf_file:
        config = ConfigParser.SafeConfigParser()
        config.read([args.conf_file])
        defaults.update(dict(config.items("Defaults")))

    # Parse rest of arguments
    # Don't suppress add_help here so it will handle -h
    parser = argparse.ArgumentParser(
        # Inherit options from config_parser
        parents=[conf_parser]
        )
    parser.set_defaults(**defaults)
    parser.add_argument("--option")
    args = parser.parse_args(remaining_argv)
    print "Option is \"{}\"".format(args.option)
    return(0)

if __name__ == "__main__":
    sys.exit(main())

关于python - 在 Python 的命令行中允许覆盖配置选项的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3609852/

相关文章:

使用基于花括号的语法读取配置文件的 C 库

python - 如何从 python 应用程序确定 X 服务器/X 转发是否正在运行?

python - 将电子邮件解析为 json 的库,就像 mailgun 所做的一样

MySQL 服务器套接字 '/tmp/mysql.sock' 连接问题

windows - 使用批处理文件提取部分文件名

linux - 在命令行中同时执行两个命令

C# COM 组件在加载到非托管 C++ 应用程序时无法读取配置

python - 使用 __repr__ 等返回 matplotlib Fig

python - vscode远程容器中的自动完成python

python - ConfigObj/ConfigParser 与为 Python 设置文件使用 YAML