Python 处理config.ini文件

在做一个自动化测试框架中需要根据不同设备修改IP、username、password等信息,开始使用excel,单使用下来发现excel较死板,不方便后续维护。且功能自动化只针对单台设备,后续需要在UI上实现。确定使用config文件,放在程序中,使用时UI直接修改即可。

先了解ini文件的格式

[common]               -----section
ip_addr = 192.168.25.71       ------option=value
username = admin
password = 123456
ssh_port = 22
telnet_port = 1723

读取和设置的代码如下

class Getipcmessage():
    def __init__(self):  ##获取配置文件路径及打开获取ini文件sections
        self.dirpwd = os.path.abspath('..') 
        self.cfgname = r'%s\Config\IPCconfig.ini' %self.dirpwd  
        self.cf = ConfigParser.ConfigParser() 
        self.cf.read(self.cfgname)
        secs = self.cf.sections()
        opts = self.cf.options("common") 
    def getcfgmessage(self):     ##获取配置文件中信息  
        self.ip = self.cf.get("common","ip_addr")
        self.username = self.cf.get("common","username")
        self.password = self.cf.get("common","password")
        self.SSH_port = self.cf.get("common","SSH_port")
        self.telnet_port = self.cf.get("common","telnet_port")      
        print self.ip,self.username,self.password,self.SSH_port
        
    def setcfgip(self,value):   ##设置IP信息到配置文件
        self.cf.set("common", "ip_addr", value)
        self.cf.write(open(self.cfgname,"w"))
        
    def setcfgusername(self,value):   ##设置username信息到配置文件
        self.cf.set("common", "username", value)
        self.cf.write(open(self.cfgname,"w"))
        
    def setcfguspassword(self,value):   ##设置password信息到配置文件
        self.cf.set("common", "password", value)
        self.cf.write(open(self.cfgname,"w"))
        
    def setcfgusshport(self,value):   ##设置ssh_port信息到配置文件
        self.cf.set("common", "ssh_port", value)
        self.cf.write(open(self.cfgname,"w"))
        
    def setcfgutelnetport(self,value):   ##设置telnet_port信息到配置文件
        self.cf.set("common", "telnet_port", value)
        self.cf.write(open(self.cfgname,"w"))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值