日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 配置文件之ConfigParser模块(实例、封装)

發布時間:2025/3/15 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 SafeConfigParserparser = 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 redisclass RedisDB(object):def __init__(self, host, port, password, db, list_name, dga_list_name):self.host = hostself.port = portself.password = passwordself.db = dbself.list_name = list_nameself.dga_list_name = dga_list_nameself.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_connexcept Exception as e:print("Redis get connect fail.")return Nonedef get_redis_data(self):try:data = self.redis_conn.rpop(self.list_name)return dataexcept Exception as e:print("Get redis data fail.")return Nonedef send_dga_result(self, result):try:self.redis_conn.lpush(self.dga_list_name, result)return Trueexcept Exception as e:print("Send dga data fail.")return Falseif __name__ == "__main__":host = "192.168.101.3"port = 6379password = "aaaaa"db = 0redis_list_name = "aaaaa"dga_list_name = "aaaa"rd = RedisDB(host, port, password, db, redis_list_name, dga_list_name)print(rd.get_redis_data())

?

總結

以上是生活随笔為你收集整理的Python 配置文件之ConfigParser模块(实例、封装)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。