Dee*_*ren 1 python configparser
我有一个属性文件
Configuration.properties
path=/usr/bin
db=mysql
data_path=/temp
Run Code Online (Sandbox Code Playgroud)
我需要读取此文件并在后续脚本中使用路径,db和data_path等变量.我可以使用configParser或只是读取文件并获取值.提前致谢.
小智 7
对于没有节标题的配置文件,包围[]- 您将发现ConfigParser.NoSectionError抛出异常.通过插入"假"部分标题来解决这个问题 - 如本答案所示.
如果文件很简单,如pcalcao的回答中所述,您可以执行一些字符串操作来提取值.
这是一个代码片段,它返回配置文件中每个元素的键值对字典.
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)
Run Code Online (Sandbox Code Playgroud)
如果您需要以简单的方式从属性文件中的某个部分读取所有值:
您的config.properties文件布局:
[SECTION_NAME]
key1 = value1
key2 = value2
Run Code Online (Sandbox Code Playgroud)
你编码:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.properties file')
details_dict = dict(config.items('SECTION_NAME'))
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个字典,其中的键与配置文件中的键及其对应的值相同。
details_dict 是 :
{'key1':'value1', 'key2':'value2'}
Run Code Online (Sandbox Code Playgroud)
现在获取 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
Run Code Online (Sandbox Code Playgroud)
现在调用上面的函数并获取所需的键值:
config_details = get_config_dict()
key_1_value = config_details['key1']
Run Code Online (Sandbox Code Playgroud)
扩展上述方法,自动逐节读取,然后按节名和键名访问。
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
Run Code Online (Sandbox Code Playgroud)
访问:
config_dict = get_config_section()
port = config_dict['DB']['port']
Run Code Online (Sandbox Code Playgroud)
(这里'DB'是配置文件中的一个部分名称,'port'是'DB'部分下的一个键。)
我喜欢目前的答案。而且...我觉得在“现实世界”中有一种更简洁的方法。如果您要进行任何规模或规模的项目,则必须使用节标题功能,尤其是在“多个”环境中。我想使用一个可靠的真实示例,将其以格式良好的可复制代码放在这里。它在Ubuntu 14中运行,但可以跨平台使用:
“基于环境”的配置
设置示例(终端):
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
Run Code Online (Sandbox Code Playgroud)
编辑属性文件。
这是您的属性文件,位于您的计算机和工作空间本地,并且包含敏感数据,请勿推送至版本控制!!!
[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
Run Code Online (Sandbox Code Playgroud)
此属性文件由所有人共享,更改已推送到版本控制
#----------------------------------------------------
# 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/
Run Code Online (Sandbox Code Playgroud)
此脚本是可重用的代码段,用于加载配置文件列表 import ConfigParser import 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
Run Code Online (Sandbox Code Playgroud)
该程序将导入上面的文件,并调用“ 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
Run Code Online (Sandbox Code Playgroud)
通过上述配置,您现在可以拥有一个脚本,该脚本可以通过更改'local.properties'中的[branch] env值来完全更改环境。而这一切都基于良好的配置原则!耶!
| 归档时间: |
|
| 查看次数: |
23175 次 |
| 最近记录: |