Python 配置文件之ConfigParser模块(实例、封装)
python3与python2使用configparser的区别
import configparser #python3中为configparser
import ConfigParser #python中为ConfigParser
一、ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69[concurrent]
thread = 10
processor = 20
括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
二、ConfigParser 初始化对象
使用ConfigParser 首选需要初始化实例,并读取配置文件:
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8")
三、ConfigParser 常用方法
1、获取所用的section节点
# 获取所用的section节点
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
print(config.sections())
#运行结果
# ['db', 'concurrent']
2、获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.options("db")
print(r)
#运行结果
# ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']
3、获取指点section下指点option的值
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.get("db", "db_host")
# r1 = config.getint("db", "k1") #将获取到值转换为int型
# r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型
# r3 = config.getfloat("db", "k3" ) #将获取到值转换为浮点型
print(r)
#运行结果
# 127.0.0.1
4、获取指点section的所用配置信息
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.items("db")
print(r)
#运行结果
#[('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')][db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root [concurrent] thread = 10 processor = 20
5、修改某个option的值,如果不存在则会出创建
# 修改某个option的值,如果不存在该option 则会创建
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
config.set("db", "db_port", "69") #修改db_port的值为69
config.write(open("ini", "w"))
6、检查section或option是否存在,bool值
import configparser config = configparser.ConfigParser() config.has_section("section") #是否存在该section config.has_option("section", "option") #是否存在该option
7、添加section 和 option
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
if not config.has_section("default"): # 检查是否存在section
config.add_section("default")
if not config.has_option("default", "db_host"): # 检查是否存在该option
config.set("default", "db_host", "1.1.1.1")
config.write(open("ini", "w"))结果
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root [concurrent] thread = 10 processor = 20 [default] db_host = 1.1.1.1
8、删除section 和 option
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") config.remove_section("default") #整个section下的所有内容都将删除 config.write(open("ini", "w"))
结果
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root [concurrent] thread = 10 processor = 20
9、写入文件
以下的几行代码只是将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效。
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8")
写回文件的方式如下:(使用configparser的write方法)
config.write(open("ini", "w"))
设置配置文件:
from configparser import SafeConfigParser
parser = SafeConfigParser()
parser.read('redis.conf')
parser.set('info', 'uptime_in_seconds', str(time))
parser.set('info', 'total_connections_received', str(connections))
parser.set('info', 'total_commands_processed', str(cmds))
Python3 实例
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import redis
class RedisDB(object):
def __init__(
self,
host,
port,
password,
db,
list_name,
dga_list_name
):
self.host = host
self.port = port
self.password = password
self.db = db
self.list_name = list_name
self.dga_list_name = dga_list_name
self.redis_conn = self.get_redis_connect()
if self.redis_conn is None:
print("Redis connect fail.")
sys.exit()
def get_redis_connect(self):
try:
redis_conn = redis.Redis(
self.host,
self.port,
self.db,
self.password,
decode_responses=True
)
return redis_conn
except Exception as e:
print("Redis get connect fail.")
return None
def get_redis_data(self):
try:
data = self.redis_conn.rpop(self.list_name)
return data
except Exception as e:
print("Get redis data fail.")
return None
def send_dga_result(self, result):
try:
self.redis_conn.lpush(self.dga_list_name, result)
return True
except Exception as e:
print("Send dga data fail.")
return False
if __name__ == "__main__":
host = "192.168.101.3"
port = 6379
password = "aaaaa"
db = 0
redis_list_name = "aaaaa"
dga_list_name = "aaaa"
rd = RedisDB(host, port, password, db, redis_list_name, dga_list_name)
print(rd.get_redis_data())
相关文章
- Node.js: Python not found exception due to node-sass and node-gyp
- python+requests接口自动化测试框架实例详解教程
- python - 如何使用 Docker 运行多个 Python 脚本和一个可执行文件?
- Python kafka操作实例(kafka-python)
- Python 字符串前面加u,r,b,f的含义(字符串前缀)
- Python flask使用实例
- 使用Python读取Mp3的标签信息
- 带你看看python的工资!你再来决定要不要学习python?
- 【Python】自动化抢勾,python软件安装教程
- 35岁了转行python可以吗?什么样的人合适学习Python?
- 零基础自学Python需要多长时间从入门到精通?学python能兼职挣钱吗?怎么挣钱?
- 《Ansible权威指南》一1.8 Python多环境扩展管理
- 泰迪云课堂大数据培训班分享Python练手题
- 《Python 3程序开发指南(第2版•修订版)》——1.3 实例
- 数据结构之四则运算表达式求值(Python和VC中缀表达式转后缀表达式实例代码)
- python 内置操作函数
- Python 教程大全之使用 python 获取唯一单词的计数
- 爬取图片实例python爬虫(保存到本地)
- Python的参数模块OptionParser说明
- Python实例---模拟微信网页登录(day4)
- Python实例---游戏人生[类的学习]
- Python实例---利用正则实现计算器[FTL版]
- [Python]Python 函数调用小例子
- Python 常见问题 之 python 安装包下载安装速度慢 的 快速解决方法(之一)
- python五十七课——正则表达式(多个字符)
- 【Python杂记】:课程表生成日历程序(生成.ics文件可直接导入日历)
- Python天气预报查询
- Python入门学习笔记第七章——输入和while~~~
- [Python] 求两个list列表的交集、并集与差集