什么';存储Python程序设置的官方方式是什么?

什么';存储Python程序设置的官方方式是什么?,python,settings,Python,Settings,Django使用真正的Python文件进行设置,Trac使用.ini文件,其他一些软件使用XML文件保存此信息 Guido和/或Python社区是否更青睐其中一种方法?我不确定是否有一种“官方”方法(在Python的禅宗中没有提到):我倾向于自己使用配置解析器模块,我想你会发现这很常见。与python文件方法相比,我更喜欢这种方法,因为如果需要,您可以写回它并动态地重新加载。为什么Guido会祝福一些超出其范围的东西?不,没有什么特别值得祝福的。它更方便。没有官方的说法。但是使用XML文件是有意

Django
使用真正的Python文件进行设置,
Trac
使用
.ini
文件,其他一些软件使用XML文件保存此信息


Guido和/或Python社区是否更青睐其中一种方法?

我不确定是否有一种“官方”方法(在Python的禅宗中没有提到):我倾向于自己使用配置解析器模块,我想你会发现这很常见。与python文件方法相比,我更喜欢这种方法,因为如果需要,您可以写回它并动态地重新加载。

为什么Guido会祝福一些超出其范围的东西?不,没有什么特别值得祝福的。

它更方便。没有官方的说法。但是使用XML文件是有意义的,因为它们可以被其他各种应用程序/库操作。

取决于主要的目标受众

如果是程序员更改了文件,只需使用像settings.py这样的python文件即可


如果是最终用户,请考虑ini文件。

这在很大程度上取决于您的配置有多复杂。如果您正在进行一个简单的键值映射,并且希望能够使用文本编辑器编辑设置,那么我认为ConfigParser是一个不错的选择

如果您的设置很复杂,并且包含列表和嵌套数据结构,我会使用XML或JSON并创建一个配置编辑器


对于真正复杂的事情,如果最终用户不希望对设置进行太多更改,或者更受信任,只需创建一组Python类并计算Python脚本即可获得配置。

不知道这是否可以被视为“正式”,但它在标准库中:


然而,这显然不是一个普遍的解决方案。只需使用最适合任务的工具,无需任何必要的复杂性(尤其是图灵完整性!请考虑自动或GUI配置程序)。

再多一个选项,PyQt。Qt有一种独立于平台的方式,可以使用QSettings类存储设置。在引擎盖下面,在windows上它使用注册表,在linux上它将设置存储在一个隐藏的conf文件中。QSettings工作得很好,而且非常简单。

正如许多人所说,没有“官方”的方法。然而,有很多选择。今年有很多可用的选项。

我使用一个书架():


对于web应用程序,我喜欢使用OS环境变量:
OS.environ.get('CONFIG_OPTION')

这对于不同部署的设置尤其有效。您可以在此处阅读更多有关使用环境变量背后的基本原理的信息:


当然,这只适用于只读值,因为对环境的更改通常不会持久。但是,如果您不需要写访问权限,它们是一个非常好的解决方案。

据我所知,没有什么好的解决方案。存储应用程序设置没有正确或错误的方法,xml、json或所有类型的文件都可以,只要您可以使用。对于python,我个人使用它非常简单、跨平台和简单

pypref非常有用,因为可以存储静态和动态设置以及首选项

from pypref import Preferences

#  create singleton preferences instance
pref = Preferences(filename="preferences_test.py")

# create preferences dict
pdict = {'preference 1': 1, 12345: 'I am a number'}

# set preferences. This would automatically create preferences_test.py 
# in your home directory. Go and check it.
pref.set_preferences(pdict)

# lets update the preferences. This would automatically update 
# preferences_test.py file, you can verify that. 
pref.update_preferences({'preference 1': 2})

# lets get some preferences. This would return the value of the preference if
# it is defined or default value if it is not.
print pref.get('preference 1')

# In some cases we must use raw strings. This is most likely needed when
# working with paths in a windows systems or when a preference includes
# especial characters. That's how to do it ...
pref.update_preferences({'my path': " r'C:\Users\Me\Desktop' "})

# Sometimes preferences to change dynamically or to be evaluated real time.
# This also can be done by using dynamic property. In this example password
# generator preference is set using uuid module. dynamic dictionary
# must include all modules name that must be imported upon evaluating
# a dynamic preference
pre = {'password generator': "str(uuid.uuid1())"}
dyn = {'password generator': ['uuid',]}
pref.update_preferences(preferences=pre, dynamic=dyn)

# lets pull 'password generator' preferences twice and notice how
# passwords are different at every pull
print pref.get('password generator')
print pref.get('password generator')

# those preferences can be accessed later. Let's simulate that by creating
# another preferences instances which will automatically detect the 
# existance of a preferences file and connect to it
newPref = Preferences(filename="preferences_test.py")

# let's print 'my path' preference
print newPref.get('my path')

最简单的使用方法之一是使用
json
模块。 将文件保存在
config.json
中,详细信息如下所示

在json文件中保存数据:

{

    "john"  : {
        "number" : "948075049" , 
        "password":"thisisit" 
    }    
}
import json

#open the config.json file 

with open('config.json') as f:
    mydata = json.load(f) ; 

#Now mydata is a python dictionary 

print("username is " , mydata.get('john').get('number') , " password is " , mydata.get('john').get('password')) ;
从json文件读取:

{

    "john"  : {
        "number" : "948075049" , 
        "password":"thisisit" 
    }    
}
import json

#open the config.json file 

with open('config.json') as f:
    mydata = json.load(f) ; 

#Now mydata is a python dictionary 

print("username is " , mydata.get('john').get('number') , " password is " , mydata.get('john').get('password')) ;

虽然不是官方的,但这种方式对我所有的Python项目都很有效

pip install python-settings
此处的文档:

您需要一个settings.py文件,其中包含所有定义的常量,如:

# settings.py

DATABASE_HOST = '10.0.0.1'
然后,您需要设置一个env变量(导出设置\u MODULE=SETTINGS)或手动调用configure方法:

# something_else.py

from python_settings import settings
from . import settings as my_local_settings

settings.configure(my_local_settings) # configure() receives a python module
该实用工具还支持重载对象的延迟初始化,因此当您运行python项目时,它的加载速度更快,因为它只在需要时计算settings变量

# settings.py

from python_settings import LazySetting
from my_awesome_library import HeavyInitializationClass # Heavy to initialize object

LAZY_INITIALIZATION = LazySetting(HeavyInitializationClass, "127.0.0.1:4222") 
# LazySetting(Class, *args, **kwargs)
只需配置一次,然后在需要时调用变量:

# my_awesome_file.py

from python_settings import settings 

print(settings.DATABASE_HOST) # Will print '10.0.0.1'

json、ini文件等也是如此。@Darren:如果您使用的是Python 2.5或更高版本(因为ElementTree),则不正确@Becominguru:XML设计目标6:“XML文档应该是人类可读的,并且相当清晰。”@S.Lott-当然应该,但这并不意味着它们真的是如此。您必须承认,编辑ini或属性文件比编辑xml文档容易得多。@Shane C.Mason:人们应该读/写xml。作为一个实际问题,这真的很难,我不太使用XML,因为它。我使用JSON或CSV文件——更容易编辑。但是@becomingGuru的评论——从狭义的技术意义上讲——是不正确的。json也在标准库中,以及所有类型的xml处理模块中。json是标准的,但这个模块之所以被称为“配置文件解析器”是有原因的。我发现它非常适合读/写,对于新手和非新手用户来说都很容易理解。@SilentGhost JSON格式不太适合人类可编辑的配置文件。--1.它不支持评论。2.许多方括号和双引号可能会让人困惑,因为您实际上回答了OPs问题(“不,没有什么特别的问题”)。反对票可能来自您答案的第一部分:社区共享“最佳实践”确实有助于开始新语言/新项目……我理解Guido的裁决在核心、stdlib开发等方面的作用。,但是问题是关于基本用法,很难定义好的实践。典型的
settings.py
文件是什么样子的?我想他指的是Django settings.py文件。它是一个有效的python文件,包含字符串、元组、列表和其他变量的声明。我同意第一部分,但如果最终用户需要修改它,您可以修改ConfigParser可以读取的内容。@mac,我找到了:@utdemir-谢谢