Python configparser 的基础使用(一)

1. 配置文件

在编写程序时,会用到一些配置。一般配置都会写入.ini的文件。如果要使用python读取配置,就可以使用python自带的configparser模块

本文首发于伊洛的个人博客:https://yiluotalk.com,欢迎关注并查看更多内容!!!

2. ini文件结构
  • 键值对可以使用' = '' : ' 分隔
  • section区分大小写
  • key的名字不区分大小写
  • 键值对中头部、尾部的空白符被去掉
  • 配置文件注释以 #或者;为开头
3. 简单的使用
  • 手写一个段代码生成ini文件
# 伊洛Yiluo
# https://yiluotalk.com
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
    'ServerAliveInterval': '45',
    'Compression': 'yes',
    'CompressionLevel': '9'
}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsectet.server.com'] = {}
topsecret = config['topsectet.server.com']
topsecret['Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)
  • 查看生成的ini文件
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsectet.server.com]
port = 50022
forwardx11 = no
4. 读取配置文件
  • 现在读取配置文件
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]

  • 由于没有读配置文件example.ini ,所以sections为空,现在读取下配置文件再查看下结果
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsectet.server.com']

  • 看到可以正常的读取到配置,再来单独的读取一条配置
>>> config['bitbucket.org']['user']
'hg'

  • 读取多条配置
>>> for i in config['DEFAULT']:
...     print(i)
... 
serveraliveinterval
compression
compressionlevel
forwardx11

5. 一般使用

通常来讲一般公司都会有几套环境:开发环境、测试环境、灰度环境、生产环境
在做接口自动化时就需要针对不同的环境跑对应的用例或是测试集,不同环境的配置就可以写入ini的配置文件方便后续调用

# 伊洛Yiluo
# https://yiluotalk.com
[test_env]
# 测试服配置
tester = 伊洛yiluo
environment = test
host =
login_name =
login_password =


[grey_env]
# 灰度服配置
tester = 伊洛yiluo
environment = grey
host =
login_name =
login_password =


[release_env]
# 正式配置
tester = 伊洛yiluo
environment = release
host =
login_name =
login_password =


[mail]
# 邮件报告配置
smtpserver =
sender =
receiver =
username =
password =


[dingding]
# dinging报告配置
robot_url =
messageUrl = 
待续…

在这里插入图片描述

关注公众号获取更多内容

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值