python单个配置文件 [英] python single configuration file

查看:79
本文介绍了python单个配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,该项目需要一个配置文件,其数据供多个模块使用。

我的问题是:通常的处理方法是什么?我应该从我的模块的每个
(文件)中读取配置文件,还是有其他方法可以这样做?

I am developing a project that requires a single configuration file whose data is used by multiple modules.
My question is: what is the common approach to that? should i read the configuration file from each of my modules (files) or is there any other way to do it?

我在想拥有一个模块名为config.py,它读取配置文件,每当我需要配置时,我都会执行 import config ,然后执行 config.data ['teamsdir' ] 获取'teamsdir'属性(例如)。

I was thinking to have a module named config.py that reads the configuration files and whenever I need a config I do import config and then do something like config.data['teamsdir'] get the 'teamsdir' property (for example).

响应:选择了conf.py方法,因为它是模块化,灵活且简单的

response: opted for the conf.py approach then since it it is modular, flexible and simple

我可以直接将配置数据放入文件中,后者,如果我想从json文件中读取xml文件或多个源,我只需更改conf.py并确保以相同的方式访问数据即可。

I can just put the configuration data directly in the file, latter if i want to read from a json file a xml file or multiple sources i just change the conf.py and make sure the data is accessed the same way.

可接受的答案:选择 Alex Martelli答复,因为该答复最完整。投票赞成其他答案,因为它们在这里也很有用。

accepted answer: chose "Alex Martelli" response because it was the most complete. voted up other answers because they where good and useful too.

推荐答案

我喜欢使用单个的方法。 config.py 模块,其主体(首次导入时)会分析一个或多个配置数据文件并适当地设置其自己的全局变量-尽管我更喜欢 config。 teamdata 绕过 config.data ['teamdata'] 方法。

I like the approach of a single config.py module whose body (when first imported) parses one or more configuration-data files and sets its own "global variables" appropriately -- though I'd favor config.teamdata over the round-about config.data['teamdata'] approach.

这假设配置设置在加载后为只读(除非在单元测试方案中,否则测试代码将对其自己的 config 变量进行人工设置以正确进行设置)练习被测代码)–它基本上利用了模块的性质,将其作为单一的最简单的Python形式(当您不需要子类或其他仅由类而不是模块支持的功能时) 。

This assumes configuration settings are read-only once loaded (except maybe in unit-testing scenarios, where the test-code will be doing its own artificial setting of config variables to properly exercise the code-under-test) -- it basically exploits the nature of a module as the simplest Pythonic form of "singleton" (when you don't need subclassing or other features supported only by classes and not by modules, of course).

一个或多个配置文件(例如, / etc 中的第一个用于常规默认设置,然后 / usr / local 下的一个特定于站点的覆盖,然后可能在用户主目录中的一个用于特定于用户的设置)是一种常见且有用的模式。

"One or more" configuration files (e.g. first one somewhere in /etc for general default settings, then one under /usr/local for site-specific overrides thereof, then again possibly one in the user's home directory for user specific settings) is a common and useful pattern.

这篇关于python单个配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆