Python ConfigParser-跨模块使用

Ste*_*ook 5 python python-module 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)
Run Code Online (Sandbox Code Playgroud)

在最后一行引用了configfile变量。这必须传递到Config模块,以便用户可以覆盖默认配置文件。我应该如何以其他模块可以使用config.get(spam,eggs)的方式在模块/类中实现此功能?

sil*_*ado 4

假设您在问题中编写的代码位于 module 内configmodule.py。然后其他模块通过以下方式访问它:

from configmodule import config
config.get(spam, eggs)
Run Code Online (Sandbox Code Playgroud)