Python ConfigParser - 跨模块使用
我正在尝试理解如何最好地使用Python的ConfigParser,这样多个程序模块都能访问配置元素。我正在使用:
import ConfigParser
import os.path
config = ConfigParser.RawConfigParser()
config.add_section('paths')
homedir = os.path.expanduser('~')
config.set('paths', 'user', os.path.join(homedir, 'users'))
[snip]
config.read(configfile)
在最后一行中提到了configfile变量。这个变量需要传递给Config模块,以便用户可以覆盖默认的配置文件。我应该如何在一个模块或类中实现这一点,以便其他模块可以使用config.get(spam, eggs)?
1 个回答
4
假设你在问题中写的代码是在一个叫做 configmodule.py
的模块里。那么其他模块可以通过以下方式来访问它:
from configmodule import config
config.get(spam, eggs)