使用python脚本编辑配置文件

时间:2017-06-02 06:00:05

标签: python automated-tests

我有一个如下所示的配置文件

....
....
MIN_TOKENS='30 50'  # can be a sequence of integers
STRIDE='2 0'  # can be a sequence of integers
SIMILARITY='1.0 0.95'  # can be a sequence of values <= 1
....
....

我需要编辑上述每个配置的参数(如果需要),并通过运行我的应用程序来测试编辑的参数是否符合我的需要。我需要使用python脚本自动执行此过程。

例如: 我需要将配置文件更改为

....
....
MIN_TOKENS='30 50'  
STRIDE='2'  
SIMILARITY='0.75'  
....
....

然后运行我的应用程序。但是,参数应该在范围内自动生成,我不应该手动输入它们。我不熟悉python。有人能告诉我如何处理这个问题。

1 个答案:

答案 0 :(得分:0)

是的,你可以做到。 你的config.ini将如下所示

[Device]
MIN_TOKENS = "34 45"
STRIDE = 45
SIMILARITY = '0.75'

conf.py

from ConfigParser import SafeConfigParser
config_file = "config.ini"
parser = SafeConfigParser()
parser.optionxform = str
parser.read(config_file)

def set_config(section, option, value):
    if parser.has_section(section):
        parser.set(section, option , value)
        with open(config_file, "w") as conf_file:
            parser.write(conf_file)
            return True
set_config('Device','MIN_TOKENS','"34 20"')

输出

[Device]
MIN_TOKENS = "34 20"
STRIDE = 45
SIMILARITY = '0.75'