在 python 中集中配置



目前我的配置选项(常量/变量)有点零散,我大部分都在 config.py,但有些在顶部的 myfile.py。

/utilities/myfile.py
/config.py

您可能会在我的 myfile.py 中找到的一个例子是:

TEMP_DIR = '/tmp'

如果我想把这个定义从我的 myfile.py 移到我的 config.py,但仍然在我的 myfile.py 中使用它,我该怎么做?

我是python的新手,但我认为它是 myfile.py 顶部

的内容
from config

变体 1

from config import *

这会在 myfile.py 中填充整个命名空间

变体 2

from config import foo, bar, baz

必须提及 myfile.py 中使用的任何值。

变体 3

import config
...
x = config.foo

每个值都需要引用配置。

您的选择,但我更喜欢变体 3。要查看 myfile.py 中的 config.py,您必须编辑 PYTHONPATH 或使用相对导入:

from ... import config

myfile.py你可以把

import config

和访问TEMP_DIR

config.TEMP_DIR

前提是包含config.py的目录位于您的 PYTHONPATH 中。

另一种方法是使用 execfile 。这将使使用不同的配置文件变得更加容易(例如,指定要在命令行上使用的配置文件)。

例:

# myconfig.py
TEMP_DIR = "/tmp/"
# myotherconfig.py
TEMP_DIR = "/tmp/foo"
# program.py (the main program)
import sys
config = {}
execfile(sys.argv[1], config)
print config["TEMP_DIR"]

调用程序:

$ python program.py myconfig.py
/tmp/
$ python program.py myotherconfig.py
/tmp/foo

相关:Python配置文件:任何文件格式推荐?INI格式仍然合适吗?似乎很老派

最新更新