San*_*nda 57 python configparser pythonpath
在开发模式下,我有以下目录树:
| my_project/
| setup.py
| my_project/
| __init__.py
| main.py
| conf/
| myproject.conf
Run Code Online (Sandbox Code Playgroud)
我使用ConfigParser来解析myproject.conf文件.
在我的代码中,使用良好的路径加载文件很容易: my_project/conf/myproject.conf
问题是:当我使用setup.py安装我的项目时,配置文件位于(感谢setup.py)/etc/my_project/myproject.conf和我的应用程序中/usr/lib/python<version>/site-packages/my_project/.
如何my_project/conf/myproject.conf在"生产"模式下在项目中引用我的文件,并my_project/conf/myproject.conf在"devel"模式下引用本地文件().
另外,如果可能的话,我想要便携式(例如在Windows上工作).
这样做的好习惯是什么?
S.L*_*ott 40
你看过配置文件是如何工作的吗?阅读"rc"文件,因为它们有时被称为."bashrc","vimrc"等
通常会对配置文件进行多步搜索.
本地目录. ./myproject.conf.
用户的主目录(~user/myproject.conf)
标准的系统范围目录(/etc/myproject/myproject.conf)
由环境变量(MYPROJECT_CONF)命名的地方
Python安装将是最后一个看的地方.
config= None
for loc in os.curdir, os.path.expanduser("~"), "/etc/myproject", os.environ.get("MYPROJECT_CONF"):
try:
with open(os.path.join(loc,"myproject.conf")) as source:
config.readfp( source )
except IOError:
pass
Run Code Online (Sandbox Code Playgroud)
更新 S.Lott 的回答。
现在该方法configparser.ConfigParser.readfp()已被弃用?
您可以configparser.ConfigParser.read()直接对多文件使用方法。
例如:
import configparser
config = configparser.ConfigParser()
all_config_files = ['/path/to/file1', '/path/to/file2', '/path/to/file3']
config.read(all_config_files)
Run Code Online (Sandbox Code Playgroud)
笔记:
read()将忽略它。read_file()请先使用。configparser.ConfigParser.read()