Best way to store config or preferences in a multi-platform way.

Matimus mccredie at gmail.com
Thu May 1 14:52:48 EDT 2008


On May 1, 4:37 am, Lance Gamet <la... at gamet.com> wrote:
> Hi, python beginner starting a new project here.
>
> This project will store most of its actual data in a shared-database, but
> I have a small amount of user specific data that I need to be stored like
> configuration or preferences for example, the list of databases that the
> program should connect to.
>
> On Unix this might be a .file, on windows this could be in the registry,
> or an ini file or an xml file in ProgramData or AppData or something.
>
> Is there a pythony way to store such config data, perhaps there is
> already a standard python package for such a purpose?
>
> My app uses Qt, and Qt has its method of doing it (QSettings), but for
> architectural reasons I don't want to use it.
>
> Could sqlite be an option perhaps? I am still undecided if the ability
> for the user to edit the file independently of the program is a good or
> bad thing.
>
> Thanks a lot.
> Lance

sqlite is a wonderful option, if the user doesn't need to directly
edit it.

Alternatively, you might consider just using python code. Something
like this:

[config_file.py]
class Config:
   optiona = 1
   optionb = 2
[/end file]

Then, in your code you can just:

>>> import imp
>>> m = imp.load_source("config_file", "./config_file.py") # use appropriate path (of course)
>>> m.Config.optiona
1
>>> m.Config.optionb
2

Like any other solution, this option has advantages and disadvantages,
but I think it is worth exploring. The class method in the above code
is just an example, choose whatever format is appropriate.

As for generating the contents of the file, tripple quoted strings and
`%r` are your friends.

Matt




More information about the Python-list mailing list