江湖道

庙堂,江湖,学术!

返回顶部

python之模块分类(四)

ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。

mysql的默认配置文件就是这样的格式:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

一、写

如果想用python生成一个文档怎么做呢?

 

#Author:Anliu
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'server_host':"DNS01",
                     'server_ip':"0.0.0.0",
                     'server_conf':"/etc/dns/name.conf"
                     }
config["user"] = {}
config["user"]["name"] = 'root'

config["pass"] = {}
top_s = config["pass"]
top_s["password"] = "123456"
top_s["pass_key"] = "/root/.ssh/key.pub"

config['DEFAULT']["server_socket"] = "/lib/dns.sock"

with open("named.conf","w") as configfile:
    config.write(configfile)

结果:

[DEFAULT]
server_host = DNS01
server_ip = 0.0.0.0
server_conf = /etc/dns/name.conf
server_socket = /lib/dns.sock

[user]
name = root

[pass]
password = 123456
pass_key = /root/.ssh/key.pub

二、读

#Author:Anliu
import configparser

config = configparser.ConfigParser()
#print(config.sections())
config.read("named.conf")
print(config.sections())
if 'DEFAULT' in config:
#    print(config['DEFAULT'])
    print(config['DEFAULT']["server_ip"])
else:
    print("NULL")

for key in config:
    print(key)

三、增删改查

#Author:Anliu
import configparser
config = configparser.ConfigParser()
config.read("i.cfg")
#print(f1)

###############查###############
#查看所有节点
secs = config.sections()
print(secs)
#查看节点下的键
options = config.options("section2")
print(options)
#查看节点下键的值
#val = config.get("section2","k1")
#print(val)
#查看节点下键的值,并将其转为整型
#val =config.getint("section2","k1")

###############删#################
#删除节点
#secs = config.remove_section("section1")
#config.write(open("i.cfg","w"))
#删除键值
#config.remove_option("section2","k1")
#config.write(open("i.cfg","w"))

###############增#################
if not config.has_section("mysql"):
    #添加节点
    config.add_section("mysql")
    config.write(open("i.cfg","w"))
else:
    print("node is exixt...")

#在node下增加键值
config.set("mysql","path","/opt/data")
config.write(open("i.cfg","w"))

################改#################
#无则添加,有则修改
config.set("mysql","path","/opt/program/data")
config.write(open("i.cfg","w"))

 

 

posted @ 2020-04-16 16:43  大江东流水  阅读(219)  评论(0编辑  收藏  举报