哪一种是允许在Python命令行中覆盖配置选项的最佳方法? [英] Which is the best way to allow configuration options be overridden at the command line in Python?

查看:93
本文介绍了哪一种是允许在Python命令行中覆盖配置选项的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with the possibility to change individual parameters at the command line when invoking the application.

现在我想使用适当的配置文件,例如ConfigParser类中的文件。同时,用户仍然应该能够在命令行上更改各个参数。

Now I would like to use 'proper' configuration files, for example from the ConfigParser class. At the same time, users should still be able to change individual parameters at the command line.

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

I was wondering if there is any way to combine the two steps, e.g. use optparse (or the newer argparse) to handle command line options, but reading the default values from a config file in ConfigParse syntax.

任何想法都可以在简单的方法?我不太喜欢手动调用ConfigParse,然后手动将所有选项的所有默认值设置为适当的值...

Any ideas how to do this in an easy way? I don't really fancy manually invoking ConfigParse, and then manually setting all defaults of all the options to the appropriate values...

推荐答案

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

I just discovered you can do this with argparse.ArgumentParser.parse_known_args(). Start by using parse_known_args() to parse a configuration file from the commandline, then read it with ConfigParser and set the defaults, and then parse the rest of the options with parse_args(). This will allow you to have a default value, override that with a configuration file and then override that with a commandline option. E.g.:

默认无用户输入:

$ ./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!"

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

Default from configuration file, overridden by commandline:

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

argprase-partial.py。正确处理 -h 有点复杂。

argprase-partial.py follows. It is slightly complicated to handle -h for help properly.

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命令行中覆盖配置选项的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆