简体   繁体   中英

How to use ConfigParser with virtualenv?

I wrote a tool that looks in several places for an INI config file: in /usr/share , /usr/local/share , ~/.local/share , and in the current directory.

c = ConfigParser.RawConfigParser()
filenames = ['/usr/share/myconfig.conf',
             '/usr/local/share/myconfig.conf',
             os.path.expanduser('~/.local/share/myconfig.conf'),
             os.path.expanduser('./myconfig.conf')]
parsed_names = c.read(filenames)
for name in parsed_names:
    print 'using configuration file: ' + name

I have started using virtualenv and now my setup.py script installs myconfig.conf into /path/to/virtual/env/share/ . How can I add this path to the list of paths searched by ConfigParser when the path to the virtualenv will be different each time? Also, if I installed to a virtualenv, should I still search the system /usr/share and /usr/local/share directories?

You should be able to get the venv share path with

os.path.join(sys.prefix, 'share', 'myconfig.conf')

Including /usr/share or /usr/local/share would depend on your application and if multiple installations by different users would be more likely to benefit or be harmed by global machine settings. Using the above code would include '/usr/share/myconfig.conf' when using the system python so it is probably safer to not include it explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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