如何读取 python 中的属性文件
How to read properties file in python
我有一个名为 Configuration.properties
的 属性 文件,其中包含:
path=/usr/bin
db=mysql
data_path=/temp
我需要读取此文件并在后续脚本中使用path
、db
和data_path
等变量。
我可以使用 configParser 或简单地读取文件并获取值来执行此操作吗?
提前致谢。
是的,是的,你可以。
ConfigParser (https://docs.python.org/2/library/configparser.html) 会给你一个很好的小结构来获取开箱即用的值,手动操作需要一些字符串拆分,但对于一个简单的格式文件来说,它并不大成交。
问题是"How do I read this file?".
对于没有部分 headers 且被 []
包围的配置文件 - 您会发现抛出 ConfigParser.NoSectionError
异常。通过插入 'fake' 部分 header 可以解决此问题 - 如 this answer.
所示
如果文件很简单,如pcalcao's answer中所述,您可以执行一些字符串操作来提取值。
这是一个代码片段,其中 returns 一个包含 key-value 对的字典,用于配置文件中的每个元素。
separator = "="
keys = {}
# I named your file conf and stored it
# in the same directory as the script
with open('conf') as f:
for line in f:
if separator in line:
# Find the name and value by splitting the string
name, value = line.split(separator, 1)
# Assign key value pair to dict
# strip() removes white space from the ends of strings
keys[name.strip()] = value.strip()
print(keys)
我喜欢当前的答案。并且...我觉得在 "Real World" 中有一种更简洁的方法。如果您正在做任何规模或规模的项目,特别是在 "multiple" 环境领域,使用 header 功能是必须的。我想把它和格式良好的 copy-able 代码放在一起,使用一个健壮的真实世界的例子。这是 Ubuntu 14 中的 运行,但适用于 cross 平台:
现实世界中的简单示例
一个'Environment-based'配置
设置示例(终端):
cd ~/my/cool/project
touch local.properties
touch environ.properties
ls -la ~/my/cool/project
-rwx------ 1 www-data www-data 0 Jan 24 23:37 local.properties
-rwx------ 1 www-data www-data 0 Jan 24 23:37 environ.properties
设置好权限
>> chmod 644 local.properties
>> chmod 644 env.properties
>> ls -la
-rwxr--r-- 1 www-data www-data 0 Jan 24 23:37 local.properties
-rwxr--r-- 1 www-data www-data 0 Jan 24 23:37 environ.properties
编辑您的属性文件。
文件 1:local.properties
这是你的属性文件,在你的机器和工作区本地,包含敏感数据,不要推送到版本控制!!!
[global]
relPath=local/path/to/images
filefilters=(.jpg)|(.png)
[dev.mysql]
dbPwd=localpwd
dbUser=localrootuser
[prod.mysql]
dbPwd=5tR0ngpwD!@#
dbUser=serverRootUser
[branch]
# change this to point the script at a specific environment
env=dev
文件 2:environ.properties
此属性文件由所有人共享,更改已推送到版本控制
#----------------------------------------------------
# Dev Environment
#----------------------------------------------------
[dev.mysql]
dbUrl=localhost
dbName=db
[dev.ftp]
site=localhost
uploaddir=http://localhost/www/public/images
[dev.cdn]
url=http://localhost/cdn/www/images
#----------------------------------------------------
# Prod Environment
#----------------------------------------------------
[prod.mysql]
dbUrl=http://yoursite.com:80
dbName=db
[prod.ftp]
site=ftp.yoursite.com:22
uploaddir=/www/public/
[prod.cdn]
url=http://s3.amazon.com/your/images/
Python 文件:readCfg.py
此脚本是一个 re-usable 片段,用于加载配置文件列表
导入配置解析器
导入 os
# a simple function to read an array of configuration files into a config object
def read_config(cfg_files):
if(cfg_files != None):
config = ConfigParser.RawConfigParser()
# merges all files into a single config
for i, cfg_file in enumerate(cfg_files):
if(os.path.exists(cfg_file)):
config.read(cfg_file)
return config
Python 文件:yourCoolProgram.py
这个程序会导入上面的文件,并调用'read_config'方法
from readCfg import read_config
#merge all into one config dictionary
config = read_config(['local.properties', 'environ.properties'])
if(config == None):
return
# get the current branch (from local.properties)
env = config.get('branch','env')
# proceed to point everything at the 'branched' resources
dbUrl = config.get(env+'.mysql','dbUrl')
dbUser = config.get(env+'.mysql','dbUser')
dbPwd = config.get(env+'.mysql','dbPwd')
dbName = config.get(env+'.mysql','dbName')
# global values
relPath = config.get('global','relPath')
filefilterList = config.get('global','filefilters').split('|')
print "files are: ", fileFilterList, "relative dir is: ", relPath
print "branch is: ", env, " sensitive data: ", dbUser, dbPwd
结论
鉴于上述配置,您现在可以拥有一个脚本,通过更改 'local.properties' 中的 [branch]env 值来完全改变环境。而这一切都是基于良好的配置原则!耶!
如果您需要以简单的方式从属性文件的某个部分读取所有值:
您的 config.properties
文件布局:
[SECTION_NAME]
key1 = value1
key2 = value2
您的代码:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.properties file')
details_dict = dict(config.items('SECTION_NAME'))
这将为您提供一个字典,其中的键与配置文件中的键及其对应的值相同。
details_dict
是:
{'key1':'value1', 'key2':'value2'}
现在获取 key1 的值:
details_dict['key1']
把它全部放在一个只从配置文件中读取该部分一次的方法中(第一次在程序中调用该方法 运行)。
def get_config_dict():
if not hasattr(get_config_dict, 'config_dict'):
get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
return get_config_dict.config_dict
现在调用上面的函数并获取所需键的值:
config_details = get_config_dict()
key_1_value = config_details['key1']
-------------------------------------------- --------------
扩展上述方法,自动逐节读取,然后按节名和键名访问。
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = dict()
for section in config.sections():
get_config_section.section_dict[section] =
dict(config.items(section))
return get_config_section.section_dict
访问:
config_dict = get_config_section()
port = config_dict['DB']['port']
(这里'DB'是配置文件中的一个段名
'port' 是 'DB' 部分下的键。)
如果你想阅读 python 中的 proeprties 文件,我的第一个建议,我自己没有遵循,因为我太喜欢 Visual Code ...
运行 是您在 Jython 上的 python 吗?
一旦你在 Jython 上 运行 python,你就可以轻松地打开一个 java util 输入流到你的数据文件。使用 java.utl.Properties 可以调用 load() api,然后就可以开始了。
所以我的建议是,做最简单的事情,开始使用 java 运行time 环境和 jython。
对了,我当然是用jython来运行python。
没有问题。
但我没有做的是使用 jython 进行调试 python...很遗憾!
我的问题是我使用 microsft visual code 编写 pythong,然后是的......然后我坚持我的正常 python 安装。
不理想的世界!
如果这是你的情况。
然后就可以去计划(b)了……
尽量不要使用 JDK 库并在其他地方找到替代方法。
所以这是建议。
这是我发现的一个库,我正在使用它来实现读取属性文件的效果。
https://pypi.python.org/pypi/jproperties/1.0.1#downloads
from jproperties import Properties
with open("foobar.properties", "r+b") as f:
p = Properties()
p.load(f, "utf-8")
# Do stuff with the p object...
f.truncate(0)
p.store(f, encoding="utf-8")
所以在上面的代码引用中,您看到了他们如何打开属性文件。
将其擦除,然后将属性再次写回到文件中。
您将属性对象视为字典对象。
然后你做这样的事情:
myPropertiesTuple = propertiesObjec[myPropertyKey]
小心。当您使用上面的 api 并获取键的值时,该值是 PropertiesTuple。它是一对(值,元数据)。因此,您要寻找的值是从 myPropertiesTuple[0] 中获取的。除此之外,只需阅读库运行良好页面上的文档即可。
我正在使用方法 (b)。
如果在某些时候使用 java 库的优势超过了坚持使用本机 python 语言的优势,那么我就可以在可视化代码上进行调试。
我会听到对纯 python 运行time 的 beat drop 支持,并将代码与硬依赖性 jython 运行time / java 库一起使用。
目前还不需要。
那么,蓝色药丸还是红色药丸?
在忽略注释的同时读取非结构化属性文件(无节)的一个衬里:
with open(props_file_path, "r", encoding="utf-8") as f:
props = {e[0]: e[1] for e in [line.split('#')[0].strip().split('=') for line in f] if len(e) == 2}
我有一个名为 Configuration.properties
的 属性 文件,其中包含:
path=/usr/bin
db=mysql
data_path=/temp
我需要读取此文件并在后续脚本中使用path
、db
和data_path
等变量。
我可以使用 configParser 或简单地读取文件并获取值来执行此操作吗?
提前致谢。
是的,是的,你可以。
ConfigParser (https://docs.python.org/2/library/configparser.html) 会给你一个很好的小结构来获取开箱即用的值,手动操作需要一些字符串拆分,但对于一个简单的格式文件来说,它并不大成交。
问题是"How do I read this file?".
对于没有部分 headers 且被 []
包围的配置文件 - 您会发现抛出 ConfigParser.NoSectionError
异常。通过插入 'fake' 部分 header 可以解决此问题 - 如 this answer.
如果文件很简单,如pcalcao's answer中所述,您可以执行一些字符串操作来提取值。
这是一个代码片段,其中 returns 一个包含 key-value 对的字典,用于配置文件中的每个元素。
separator = "="
keys = {}
# I named your file conf and stored it
# in the same directory as the script
with open('conf') as f:
for line in f:
if separator in line:
# Find the name and value by splitting the string
name, value = line.split(separator, 1)
# Assign key value pair to dict
# strip() removes white space from the ends of strings
keys[name.strip()] = value.strip()
print(keys)
我喜欢当前的答案。并且...我觉得在 "Real World" 中有一种更简洁的方法。如果您正在做任何规模或规模的项目,特别是在 "multiple" 环境领域,使用 header 功能是必须的。我想把它和格式良好的 copy-able 代码放在一起,使用一个健壮的真实世界的例子。这是 Ubuntu 14 中的 运行,但适用于 cross 平台:
现实世界中的简单示例
一个'Environment-based'配置
设置示例(终端):
cd ~/my/cool/project touch local.properties touch environ.properties ls -la ~/my/cool/project -rwx------ 1 www-data www-data 0 Jan 24 23:37 local.properties -rwx------ 1 www-data www-data 0 Jan 24 23:37 environ.properties
设置好权限
>> chmod 644 local.properties
>> chmod 644 env.properties
>> ls -la
-rwxr--r-- 1 www-data www-data 0 Jan 24 23:37 local.properties
-rwxr--r-- 1 www-data www-data 0 Jan 24 23:37 environ.properties
编辑您的属性文件。
文件 1:local.properties
这是你的属性文件,在你的机器和工作区本地,包含敏感数据,不要推送到版本控制!!!
[global]
relPath=local/path/to/images
filefilters=(.jpg)|(.png)
[dev.mysql]
dbPwd=localpwd
dbUser=localrootuser
[prod.mysql]
dbPwd=5tR0ngpwD!@#
dbUser=serverRootUser
[branch]
# change this to point the script at a specific environment
env=dev
文件 2:environ.properties
此属性文件由所有人共享,更改已推送到版本控制
#----------------------------------------------------
# Dev Environment
#----------------------------------------------------
[dev.mysql]
dbUrl=localhost
dbName=db
[dev.ftp]
site=localhost
uploaddir=http://localhost/www/public/images
[dev.cdn]
url=http://localhost/cdn/www/images
#----------------------------------------------------
# Prod Environment
#----------------------------------------------------
[prod.mysql]
dbUrl=http://yoursite.com:80
dbName=db
[prod.ftp]
site=ftp.yoursite.com:22
uploaddir=/www/public/
[prod.cdn]
url=http://s3.amazon.com/your/images/
Python 文件:readCfg.py
此脚本是一个 re-usable 片段,用于加载配置文件列表 导入配置解析器 导入 os
# a simple function to read an array of configuration files into a config object
def read_config(cfg_files):
if(cfg_files != None):
config = ConfigParser.RawConfigParser()
# merges all files into a single config
for i, cfg_file in enumerate(cfg_files):
if(os.path.exists(cfg_file)):
config.read(cfg_file)
return config
Python 文件:yourCoolProgram.py
这个程序会导入上面的文件,并调用'read_config'方法
from readCfg import read_config
#merge all into one config dictionary
config = read_config(['local.properties', 'environ.properties'])
if(config == None):
return
# get the current branch (from local.properties)
env = config.get('branch','env')
# proceed to point everything at the 'branched' resources
dbUrl = config.get(env+'.mysql','dbUrl')
dbUser = config.get(env+'.mysql','dbUser')
dbPwd = config.get(env+'.mysql','dbPwd')
dbName = config.get(env+'.mysql','dbName')
# global values
relPath = config.get('global','relPath')
filefilterList = config.get('global','filefilters').split('|')
print "files are: ", fileFilterList, "relative dir is: ", relPath
print "branch is: ", env, " sensitive data: ", dbUser, dbPwd
结论
鉴于上述配置,您现在可以拥有一个脚本,通过更改 'local.properties' 中的 [branch]env 值来完全改变环境。而这一切都是基于良好的配置原则!耶!
如果您需要以简单的方式从属性文件的某个部分读取所有值:
您的 config.properties
文件布局:
[SECTION_NAME]
key1 = value1
key2 = value2
您的代码:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.properties file')
details_dict = dict(config.items('SECTION_NAME'))
这将为您提供一个字典,其中的键与配置文件中的键及其对应的值相同。
details_dict
是:
{'key1':'value1', 'key2':'value2'}
现在获取 key1 的值:
details_dict['key1']
把它全部放在一个只从配置文件中读取该部分一次的方法中(第一次在程序中调用该方法 运行)。
def get_config_dict():
if not hasattr(get_config_dict, 'config_dict'):
get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
return get_config_dict.config_dict
现在调用上面的函数并获取所需键的值:
config_details = get_config_dict()
key_1_value = config_details['key1']
-------------------------------------------- --------------
扩展上述方法,自动逐节读取,然后按节名和键名访问。
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = dict()
for section in config.sections():
get_config_section.section_dict[section] =
dict(config.items(section))
return get_config_section.section_dict
访问:
config_dict = get_config_section()
port = config_dict['DB']['port']
(这里'DB'是配置文件中的一个段名 'port' 是 'DB' 部分下的键。)
如果你想阅读 python 中的 proeprties 文件,我的第一个建议,我自己没有遵循,因为我太喜欢 Visual Code ...
运行 是您在 Jython 上的 python 吗? 一旦你在 Jython 上 运行 python,你就可以轻松地打开一个 java util 输入流到你的数据文件。使用 java.utl.Properties 可以调用 load() api,然后就可以开始了。 所以我的建议是,做最简单的事情,开始使用 java 运行time 环境和 jython。
对了,我当然是用jython来运行python。 没有问题。
但我没有做的是使用 jython 进行调试 python...很遗憾! 我的问题是我使用 microsft visual code 编写 pythong,然后是的......然后我坚持我的正常 python 安装。 不理想的世界!
如果这是你的情况。 然后就可以去计划(b)了…… 尽量不要使用 JDK 库并在其他地方找到替代方法。
所以这是建议。 这是我发现的一个库,我正在使用它来实现读取属性文件的效果。 https://pypi.python.org/pypi/jproperties/1.0.1#downloads
from jproperties import Properties with open("foobar.properties", "r+b") as f: p = Properties() p.load(f, "utf-8") # Do stuff with the p object... f.truncate(0) p.store(f, encoding="utf-8")
所以在上面的代码引用中,您看到了他们如何打开属性文件。 将其擦除,然后将属性再次写回到文件中。
您将属性对象视为字典对象。 然后你做这样的事情:
myPropertiesTuple = propertiesObjec[myPropertyKey]
小心。当您使用上面的 api 并获取键的值时,该值是 PropertiesTuple。它是一对(值,元数据)。因此,您要寻找的值是从 myPropertiesTuple[0] 中获取的。除此之外,只需阅读库运行良好页面上的文档即可。
我正在使用方法 (b)。 如果在某些时候使用 java 库的优势超过了坚持使用本机 python 语言的优势,那么我就可以在可视化代码上进行调试。
我会听到对纯 python 运行time 的 beat drop 支持,并将代码与硬依赖性 jython 运行time / java 库一起使用。 目前还不需要。
那么,蓝色药丸还是红色药丸?
在忽略注释的同时读取非结构化属性文件(无节)的一个衬里:
with open(props_file_path, "r", encoding="utf-8") as f:
props = {e[0]: e[1] for e in [line.split('#')[0].strip().split('=') for line in f] if len(e) == 2}