0

I have terrible doubts regarding python config file approach.

I am creating a program with a GUI (PyQt). The program loads some settings from a .cfg file using the configparser module. And the user can edit these settings from the GUI with the user preferences widget. When the preferences widget is closed the .cfg file is saved but I don't know how to update the rest of the program using the updated settings values.

I will try to explain with an example:

  1. I launch the program. It create a ConfigParser() named config and read settings.cfg.
  2. The program retrieve the value of the option 'clock_speed' (let's say it is 5) from config and set clkSpd = 5.
  3. I click on Edit -> Preferences and change the clock speed via a QSpinBox to 8.
  4. I close the Preferences windget, settings.cfg is saved, the value of the option 'clock_speed' is now 8.
  5. BUT in its module, clkSpd is still 5.

I know I can just load the settings, edit them, save them and reload all settings each time I close the Preferences window. It's simple but not very beautiful.

Is there a classic and effficiant approach for config files in read/write mode ?

Thanks by advance.

selfm
  • 101
  • 1
  • 9

2 Answers2

0

Try adding a callback to your preferences widget so that when it is closed, any changed values are propagated back to the rest of the program. Events or signal handling like this overview may work for you.

You also may need to rearrange where those variables are stored to be able to modify them from a callback. This may be a good application for globals, or you may check out this SO question to see if you can have the variables passed into your callbacks for update.

Community
  • 1
  • 1
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
0

Updating the state of your application may not be a trivial thing if you are somewhere in the middle. Just an example:

  1. Your app = A car
  2. You launch your app = You start your car
  3. You set in the preferences the variable type_tyre to Winter
  4. Your running app still has type_tyre equals Sommer
  5. You attempt to change tyres while driving on the highway
  6. Crash

And this while changing the tyres before starting the car might be a trivial and safe thing to do.

So you just have to write a routine that adjusts the state of your application according to the change in preferences but this is in general different from initializing the app and depends on the current state of the app. But otherwise just write such a routine and call it.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104