17

I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability.

I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a place to store it that will work in virtualenv, the users home directory etc. I want it to be as close to how normal Unix packages work, i.e. have config in etc, but with overrides in home directory. Is there a readymade solution for this, and if not, what should I put in my setup.py etc to make it work like I want?

Joakim Lundborg
  • 10,920
  • 6
  • 32
  • 39

1 Answers1

13

you can use data_files option of distutils to install files wherever you want.

data_files specifies a sequence of (directory, files) pairs in the following way:

setup(...,
      data_files=[('/etc', ['cfg/config1.ini', 'cfg/config2.ini']),
                  ('/etc/init.d', ['bin/initscript1'])],
      ....
     )

When reading the config file on your app, you can merge a /home version if it exists, using .read() method of ConfigParser objects:

files_read = cfgparserobj.read(['/etc/config1.ini', 
                                os.path.expanduser('~/.config1.ini')])
for fname in files_read:
    print "Reading config from", fname

That will read /etc/config1.ini and then overwrite the definitions with stuff coming from .config1.ini in the user's home directory, if it exists.

nosklo
  • 217,122
  • 57
  • 293
  • 297
  • 6
    Is there a way to make this work nice with virtualenv? I.e. what path should I specify to put stuff in myvirtenv/etc/myconf.ini ? – Joakim Lundborg Jan 08 '10 at 14:38
  • 4
    I know this is an old post, but still can be usefull. @JoakimLundborg: you can use ``sys.prefix``, which is by default ``/usr``, and the path of your virtualenv in your case (with the real prefix in ``sys.real_prefix`` – linkdd May 03 '14 at 00:55
  • Using sys.real_prefix seems very promising, it would require also a way to get the same location at runtime to read the configuration file from there; can the same be used for that purpose? – a1an Nov 18 '16 at 10:34