Sharing settings\\constants between Python projects

爱⌒轻易说出口 提交于 2019-12-04 20:21:00

I find that in many cases, using a configuration file is really worth the (minor) hassle. The builtin ConfigParser module is very handy, especially the fact that it's really easy to parse multiple files and let the module merge them together, with values in files parsed later overriding values from files parsed earlier. This allows for easy use of a global file (e.g. /etc/yoursoftware/main.ini) and a per-user file (~/.yoursoftware/main.ini).

Each of your projects would then open the config file and read values from it.

Here's a small code example:

basefile.ini:

[sect1]
value1=1
value2=2

overridingfile.ini:

[sect1]
value1=3

configread.py:

#!/usr/bin/env python

from ConfigParser import ConfigParser

config = ConfigParser()
config.read(["basefile.ini", "overridingfile.ini"])

print config.get("sect1", "value1")
print config.get("sect1", "value2")

Running this would print out:

3
2

Why don't you just have a file named constants.py and just have CONSTANT = value

Create a Python package and import it in the various projects...

Why is a database overkill? You're describing sharing data across different projects located on different physical systems with different paths to each project's directory. Oh, and sometimes the projects just aren't there. I can't imagine a better means of communicating the data. It only has to be a single table, that's hardly overkill if it provides the consistent access you need across platforms, computers, and even networks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!