如何在虚拟环境中使用ConfigParser?
我写了一个工具,它会在几个地方寻找一个INI配置文件:在 /usr/share
、/usr/local/share
、~/.local/share
和当前目录。
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/
。我该如何把这个路径添加到ConfigParser搜索的路径列表中,因为虚拟环境的路径每次都可能不同?另外,如果我安装在虚拟环境中,是否还应该继续搜索系统的 /usr/share
和 /usr/local/share
目录呢?
1 个回答
1
你可以通过下面的方式获取虚拟环境的共享路径:
os.path.join(sys.prefix, 'share', 'myconfig.conf')
是否要包含 /usr/share
或 /usr/local/share
取决于你的应用程序,以及不同用户的多个安装是否更可能从全局机器设置中受益或受到影响。使用上面的代码时,如果你用的是系统自带的 Python,它会包含 '/usr/share/myconfig.conf'
,所以最好不要明确地包含它。