Editing the configuration file using python script

谁说胖子不能爱 提交于 2020-07-20 06:09:46

问题


I have a config file like below

....
....
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
....
....

I need to edit the parameters to each of the above configurations(if needed) and test if the edited parameter suits my need by running my application. I need to automate this process using python script.

For example: I need to change the config file to something like

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

and then run my application. However, the parameters should be automatically generated within range and I shouldn't manually feed them. I'm not familiar with python. Could someone tell me how to approach this.


回答1:


yes you can do. your config.ini will be something like below

[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"')

output

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


来源:https://stackoverflow.com/questions/44321825/editing-the-configuration-file-using-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!