使用 Python 创建动态配置文件

156 阅读2分钟

我们有一个 Python 脚本,它由一个名为 system.config 的配置文件控制。配置文件的结构如下,其中包含一些默认值:

huake_00063_.jpg

[company]
companyname: XYZ

[profile]
name: ABC
joining: 1/1/2014

配置文件的 Python 代码在 config_parser_details.py 文件中:

import ConfigParser
import sys

Config = ConfigParser.ConfigParser()
Config.read("system.config")
filename = "system.config"

def ConfigSectionMap(section):
  dict1 = {}
  options = Config.options(section)
  for option in options:    
    try:
      dict1[option] = Config.get(section, option)
      if dict1[option] == -1:
         DebugPrint("skip: %s" % option)
    except:
      print("exception on %s!" % option)
      dict1[option] = None
  return dict1

company = ConfigSectionMap("company")['companyname']
name = ConfigSectionMap("profile")['name']
joindate = ConfigSectionMap("profile")['joining']

脚本的代码在 test.py 文件中:

import config_parser_details as p
import sys
import warnings
import os

company = p.company

name = p.name
date = p.joindate


print("%s\n" %company)
print("%s\n" %name)

输出结果为:

XYZ
ABC

现在,我们希望通过命令行向配置文件中输入数据。例如:

python test.py --compname ="testing"

如果命令行中缺少任何参数,则使用默认值作为输入。

2. 解决方案

我们可以使用 docopt 工具来实现这个功能。docopt 能够将命令行参数解析为 Python 数据结构。

在 test.py 文件中,我们将 ConfigSectionMap 函数修改如下:

def ConfigSectionMap(section):
  options = Config.options(section)

  arg_dict = {}
  for command_line_argument in sys.argv[1:]:
    arg = command_line_argument.split("=")
    arg_dict[arg[0][2:]] = arg[1]

  for key in arg_dict:
    options[key] = arg_dict[key]

  return options

这样,我们就可以在命令行中传入参数来覆盖或添加配置文件中的选项。

例如,我们可以运行以下命令来将公司名称设置为 "testing":

python test.py --compname ="testing"

输出结果为:

testing
ABC

我们也可以使用 argparse 库来解析命令行参数。argparse 是 Python 标准库中的一个模块,它提供了一个更强大的命令行参数解析器。

将 test.py 文件修改如下:

import config_parser_details as p
import sys
import warnings
import os
import argparse

commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-c", "--compname", help="Company name", default=p.company)
commandLineArguments = commandLineArgumentParser.parse_args()

company = commandLineArguments.compname

name = p.name
date = p.joindate

print("%s\n" %company)
print("%s\n" %name)

现在,我们可以运行以下命令来将公司名称设置为 "testing":

python test.py -c "testing"

输出结果为:

testing
ABC

使用 argparse 库的好处是,它可以自动生成命令行帮助信息。我们可以使用以下命令查看帮助信息:

python test.py --help

输出结果为:

usage: test.py [-h] [-c COMPNANE]

optional arguments:
  -h, --help  show this help message and exit
  -c COMPNANE, --compname COMPNANE
                        Company name (default: XYZ)

这样,我们就通过命令行参数的方式动态地修改了配置文件。