Sharing settings\constants between Python projects

北城余情 提交于 2020-01-13 06:28:25

问题


What would be a neat way to share configuration parameters\settings\constants between various projects in Python?

Using a DB seems like an overkill. Using a file raises the question of which project should host the file in its source control...

I'm open for suggestions :)

UPDATE:
For clarification - assume the various projects are deployed differently on different systems. In some cases in different directories, in other cases some of the projects are there and some are not.


回答1:


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



回答2:


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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/6805977/sharing-settings-constants-between-python-projects

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