在运行时重写配置文件

Rewriting configuration file at runtime

我在 python3.7.1.
中通过 configparser 使用配置文件 我想在运行时修改其中一个文件中的一个变量,想知道什么是最好的方法。

现在我重写了整个文件:

config = configparser.ConfigParser()
config.read('config.ini')
config['Categorie']['new_variable'] = variable
with open('config.ini', 'w') as configfile:
    config.write(configfile)

我对这种方法有 2 个顾虑:

configparser 不存储评论,所以你会卡在那个评论上,除非你 使用这个模块......或者你可以提取注释并随后将它们重新注入文件(丢失注释的位置,但保留内容)

为避免在出现错误(磁盘已满或其他)时丢失配置,您可以另存为其他名称,删除当前文件并重命名。

conf_file = 'config.ini'
with open(conf_file+'.bak', 'w') as configfile:
    config.write(configfile)
if os.path.exists(conf_file):
   os.remove(conf_file)  # else rename won't work when target exists
os.rename(conf_file+'.bak',conf_file)

这种方法是安全的。如果无法写入文件,则不会破坏先前的文件。最坏的情况是(如果有人在删除原始文件的 确切 时刻拔下插头).bak 文件(具有适当的新内容)仍然存在。

另一种方法是重命名现有的 .ini 文件,写入新文件,并在文件成功写入后删除旧的 .ini 文件。

所有操作都在同一驱动器上执行,因此即使文件很大,也不会再进行磁盘访问(重命名除外)。

config.ini

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = {somelevel}
ForwardX11 = yes

python代码

content = open('config.ini').read()
somelevel = 34
filled = content.format(**locals())
gg = ConfigParser()
gg.read_string(filled)

但是,不要对真实代码使用 **locals()。 请尝试寻找更好的方法,这很脏。

编辑:我尝试做一些简单的 f 字符串破解,但由于转义问题而失败。