Python学习笔记之configparser配置文件以及traceback异常处理

import os, configparser, traceback

SETTINGS = "Settings"
ENTRY = ['SFB', 'MTF', 'MBF', 'DSP', 'ECK', 'TUD']

class fileListConfig:
    _code_image = './Code_Image/'
    _eck_image = './ECK_Image/'

    def __init__(self):
        self.cf = configparser.ConfigParser()

    def getPath(self, folder, file):
        realPath = os.path.dirname(os.path.realpath(__file__))
        '''路径拼接'''
        return '/'.join([realPath, folder, file])

    def getImage(self):

        # TEMP_DIR = 'I:/mainline/SDK/Daily_build_sdk/2019-02-27'
        # os.chdir(TEMP_DIR)
        
        '''增加Section'''
        self.cf.add_section(SETTINGS)

        try:

            for file in os.listdir(self.__class__._code_image):
                if file.lower().endswith('bin'):
                    if file.lower().find('boot') >= 0:
                        self.cf.set(SETTINGS, ENTRY[0], self.getPath(self.__class__._code_image, file))
                    elif file.lower().find('top') >= 0:
                        self.cf.set(SETTINGS, ENTRY[1], self.getPath(self.__class__._code_image, file))
                    elif file.lower().find('bt') >= 0:
                        self.cf.set(SETTINGS, ENTRY[2], self.getPath(self.__class__._code_image, file))
                    elif file.lower().find('dsp') >= 0:
                        self.cf.set(SETTINGS, ENTRY[3], self.getPath(self.__class__._code_image, file))

            for file in os.listdir(self.__class__._eck_image):
                if file.lower().endswith('vfi'):
                    self.cf.set(SETTINGS, ENTRY[4].upper(), self.getPath(self.__class__._eck_image, file))

            self.cf.write(open('fileList.zfg', 'w'))

        except Exception as E:
            print('str(Exception):', str(Exception))
            print('str(e):', str(E))
            print('repr(e):', repr(E))
            print('traceback.print_exc(): ', traceback.print_exc())
            print('traceback.format_exc(): %s' % traceback.format_exc())


if __name__ == '__main__':

    fileList = fileListConfig()
    fileList.getImage()

示例说明:

1、str(e)

   返回字符串类型,只给出异常信息,不包括异常信息的类型

2、repr(e)

   给出较全的异常信息,包括异常信息的类型

3、采用traceback模块

   需要导入traceback模块,此时获取的信息最全,与python命令行运行程序出现错误信息一致。使用    
    traceback.print_exc()打印异常信息到标准错误,就像没有获取一样,或者使用
    traceback.format_exc()将同样的输出获取为字符串。你可以向这些函数传递各种各样的参数来限制输
    出,或者重新打印到像文件类型的对象。

示例输出结果:

[Settings]
dsp = I:/mainline/SDK/Beta/SDK/V014\./Code_Image/dsp.bin
sfb = I:/mainline/SDK/Beta/SDK/V014\./Code_Image/SBootloader_release.bin
mbf = I:/mainline/SDK/Beta/SDK/V014\./Code_Image/bt_release_en.bin
mtf = I:/mainline/SDK/Beta/SDK/V014\./Code_Image/top.bin
eck = I:/mainline/SDK/Beta/SDK/V014\./ECK_Image/TriCore_TriMode_V0.3.8.vfi

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值