简体   繁体   English

如果在程序运行时重新启动,使用 configparser 写入 .ini 文件会导致一个空文件

[英]Writing to an .ini file using configparser results in an empty file if restarted while program is running

I have a program that runs a method every five seconds.我有一个程序每五秒运行一个方法。 In this method, I require writing to the configuration .ini file and, because this is embedded software, it must be able to handle the system shutting down at unknown times.在这种方法中,我需要写入配置 .ini 文件,因为这是嵌入式软件,它必须能够处理系统在未知时间关闭的情况。 However, every time the system shuts down while the program is running, the .ini file is empty when the system starts up again.但是,每次在程序运行时系统关闭,当系统再次启动时,.ini 文件都是空的。

Here is the code for the method being run:这是正在运行的方法的代码:

def HandleBatteryMonitoring():
    #some code before this...
    systemConfig = ConfigObj('settings.ini')
    systemConfig.filename = 'settings.ini'

    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryMSB)
    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryLSB)
    systemConfig['systemsettings']['batterydischargebusmsb'] = str(dischargeBatteryMSB)
    systemConfig['systemsettings']['batterydischargebuslsb'] = str(dischargeBatteryLSB)
    systemConfig['systemsettings']['batterypercentage'] = str(batteryPercentage)

    systemConfig.write()

Currently it is using ConfigObj, but only because the same problem happened with ConfigParser, and I was hoping a different library would help the problem.目前它正在使用 ConfigObj,但只是因为 ConfigParser 发生了同样的问题,我希望不同的库可以帮助解决这个问题。 Here's the same code when it used ConfigParser:这是使用 ConfigParser 时的相同代码:

def HandleBatteryMonitoring():
    #some code before this...
    systemConfig = configparser.ConfigParser('settings.ini')

    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryMSB)
    systemConfig['systemsettings']['batterychargebuslsb'] = str(chargingBatteryLSB)
    systemConfig['systemsettings']['batterydischargebusmsb'] = str(dischargeBatteryMSB)
    systemConfig['systemsettings']['batterydischargebuslsb'] = str(dischargeBatteryLSB)
    systemConfig['systemsettings']['batterypercentage'] = str(batteryPercentage)

    with open('settings.ini', 'w') as file:
        systemConfig.write(file)

That method is called from here:从这里调用该方法:

def OnHandleCharging():
    while True:
        HandleBatteryCharging()
        time.sleep(5)

It should be noted that, while the program is running, the file is being written to correctly, and I can watch the values changing as the file changes.应该注意的是,当程序运行时,文件正在被正确写入,我可以看到值随着文件的变化而变化。 This only happens when the system is restarted during operation.这仅在系统在运行期间重新启动时发生。

I need this config file to not be emptied upon restarting.我需要这个配置文件在重新启动时不被清空。 Any solutions or workarounds for this would be greatly appreciated.对此的任何解决方案或解决方法将不胜感激。

尝试以 'r+' 格式打开文件并更改值,如果您用 'w' 打开文件,它可能会覆盖文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM