2010-10-21 55 views
0

我写了一个工具,在几个地方查找一个INI配置文件:在/usr/share,/usr/local/share,~/.local/share和当前目录中。如何在virtualenv中使用ConfigParser?

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 

我一直在使用的virtualenv开始了,现在我的setup.py脚本安装myconfig.conf/path/to/virtual/env/share/。当virtualenv的路径每次都会有所不同时,如何将此路径添加到由ConfigParser搜索的路径列表中?另外,如果我安装到virtualenv,我还应该搜索系统/usr/share/usr/local/share目录吗?

回答

1

你应该能够

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

包括/usr/share/usr/local/share将取决于您的应用程序,如果多个安装由不同的用户更有可能受益或受到全球机器受到伤害获得VENV共享路径设置。当使用系统python时,使用上面的代码将包括'/usr/share/myconfig.conf',所以不明确包含它可能更安全。

+0

谢谢马克,我认为sys.prefix是一个很好的解决方案。 – 2010-10-21 19:18:48