configparser模块
1. 使用configparser模块生成配置文件
import configparser config = configparser.ConfigParser() config["client"] ={ "port": 3306, "socket": "/tmp/mysql.sock" } config["mysqld"] = { "port": 3306, "socket": "/tmp/mysql.sock", "basedir":"/usr/local/mysql", "datadir": "/data/mysql", "pid-file": "/data/mysql/mysql.pid", "user": "mysql", "bind-address": "0.0.0.0", "server-id": 1, "max_connections": 1000 } config["mysqldump"] = { "max_allowd_packet": "16M" } with open("mysql.cnf",'w') as f: config.write(f)
生成的配置文件内容如下:
2. 读取配置文件
import configparser conf = configparser.ConfigParser() conf.read("mysql.cnf") print(conf.sections()) # ['client', 'mysqld', 'mysqldump'] print(conf["client"]["port"]) # 3306 print(conf["mysqld"]["bind-address"]) # 0.0.0.0 print(conf["mysqldump"]["max_allowd_packet"]) # 16M
博主小学未毕业,请勿口喷!