Python读取cfg文件

本文介绍了一个使用Python从本地配置文件中读取MySQL和Redis连接信息的例子。通过ConfigParser模块解析配置文件,利用pymysql模块连接MySQL数据库并执行SQL查询,展示了一种常见的后台开发场景。

    

[mysql]
HOST = 127.0.0.1
PORT = 3306
USER = root
PWD = 123456789
DB = employees
CHARSET = utf8


[redis]
# #redis配置,暂时写在这里,线下配置。线上一定要从新配置,并且不要上传到gitlab。 非常重要!!!
HOST = 127.0.0.1
PORT = 6379
PWD =
DBID = 0


import pymysql
import configparser
cp = configparser.ConfigParser()
cp.read('test.cfg')
conn = pymysql.connect(
        host = cp.get('mysql', 'HOST'),
        user = cp.get('mysql', 'USER'),
        passwd = cp.get('mysql', 'PWD'),
        db = cp.get('mysql', 'DB'),
        port = cp.getint('mysql', 'PORT'),
        charset= cp.get("mysql", 'CHARSET'),
    )
cur = conn.cursor()
sql="""select * from mushroom"""
cur.execute(sql)
data=cur.fetchall()
print(data)



### PythonCFG 配置文件的创建与读取 #### 创建 CFG 文件Python 中,`ConfigParser` 模块提供了方便的方法来处理 `.cfg` 或其他类型的配置文件。为了创建一个 `cfg` 文件,在项目目录结构中建立一个新的配置文件并编写相应的键值对。 ```ini # config.cfg [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no ``` 此段代码展示了如何构建一个简单的 `cfg` 文件[^2]。 #### 使用 ConfigParser 读取 CFG 文件读取上述创建好的配置文件,需先导入 `configparser` 库,并初始化一个 `ConfigParser` 对象实例化之后加载指定路径下的配置文件: ```python import configparser # 初始化配置解析器对象 config = configparser.ConfigParser() # 加载配置文件 config.read('path/to/config.cfg') # 获取特定部分中的选项值 server_alive_interval = config.getint('DEFAULT', 'ServerAliveInterval') compression_level = config.getint('DEFAULT', 'CompressionLevel') forward_x11_bitbucket = config.getboolean('bitbucket.org', 'ForwardX11') port_topsecret = config.getint('topsecret.server.com', 'Port') print(f"Server Alive Interval: {server_alive_interval}") print(f"Compression Level: {compression_level}") print(f"Bitbucket Forward X11: {'Yes' if forward_x11_bitbucket else 'No'}") print(f"Top Secret Server Port: {port_topsecret}") ``` 这段脚本演示了怎样利用 `ConfigParser` 类从已有的 `cfg` 文件里提取数据。 #### 修改和保存 CFG 文件 除了读取之外,还可以修改现有的设置并将更改回存到磁盘上: ```python # 更新现有条目 config.set('DEFAULT', 'ServerAliveInterval', str(60)) with open('path/to/config.cfg', 'w') as configfile: config.write(configfile) ``` 这允许动态调整应用程序的行为而无需重新编译源码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值