如何使用python创建动态配置文件

2024-05-18 11:06:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,它由一个名为的配置文件控制系统配置。配置文件的结构类似于下面的一些默认值。在

[company]
companyname: XYZ

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

配置文件的代码是:配置分析器_详细信息.py

^{pr2}$

现在我的脚本代码是:测试.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"

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


Tags: 代码命令行namepyimport脚本配置文件profile
3条回答

您可以使用argparse库来分析命令行参数。在

所以你的测试.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)

我建议你研究一下像docopt这样的工具。在

为了快速解决问题,你可以试试这个

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

这将加载所有默认选项。任何放在命令行上的选项都将覆盖或添加到选项dict中

首先,我将代码移到main部分,这样您就可以import config_parser_details而不执行代码:

if __name__ == '__main__':
    main()

def main():
    Config = ConfigParser.ConfigParser()
    Config.read("system.config")
    filename = "system.config"

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

其次,我将使用STB land的建议,即使用argparse解析命令行,类似于:

^{pr2}$

通过这种方式,您可以灵活地使用python自己的unit test frameworknosetests编写不需要您手动指定参数的测试文件:

def test_basic():
    # create a temporary file with tempfile.NamedTemporaryFile
    tmpfile = tempfile.NamedTemporaryFile()
    # add test data to tmpfile
    do_stuff(tmpfile)

    # check the output
    assert .... 

这带来了一个额外的好处,即没有全局变量,这会使你以后的生活变得复杂。在

相关问题 更多 >