50.python读取ini配置文件与使用日志模块logging记录日志信息保存日志文件

50.读取ini配置文件与使用日志模块logging记录日志信息保存日志文件

dept.ini

[robots]
fxl: L223
ttw: L856
ssy: M398
result_msg: this is ini file
pii:3.625412
[visions]
ll:k566
zel:please key in msg:
dcb:m921

 

x

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('good luck')
    from configparser import ConfigParser
    CONFIGFILE = 'dept.ini'
    config = ConfigParser()
    config.read(CONFIGFILE)
    print(config['robots'].get('fxl'))
    #radius = float(input(config['visions'].get('zel')))
    print(config['robots'].get('result_msg'), end='')
    print('')
    print('pii*2=', config['robots'].getfloat('pii')**2)

    #python日志模块
    import logging
    # logging.basicConfig(level=logging.INFO,filename='ta.log')
    # logging.info('Staring program')
    # logging.info('recv error')
    # logging.info('vision is ok')
    # logging.info('mc end')

    # !/usr/bin/env python
    # -*-coding:UTF-8-*-
    import logging
    import time
    import os

    # 创建Logger对象
    logger = logging.getLogger('tt_logger')
    logger.setLevel(logging.DEBUG)

    # 创建文件处理程序
    log_file_path = os.getcwd() +'\\log\\'
    if not os.path.exists(log_file_path):
        os.makedirs(log_file_path)  # 创建目录,目录存在不会报异常
    print(log_file_path + time.strftime('%Y%m%d', time.localtime()) + '.txt')
    file_handler = logging.FileHandler(log_file_path+time.strftime('%Y%m%d', time.localtime())+'.txt', mode='w')
    # 定义日志格式
    #formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    formatter = logging.Formatter('%(asctime)s %(message)s')

    # 为文件处理程序添加格式化器
    file_handler.setFormatter(formatter)

    # 将文件处理程序添加到Logger对象上
    logger.addHandler(file_handler)

    # 测试日志记录
    logger.debug("This is a debug message.")
    logger.info("This is an info message.")
    logger.warning("This is a warning message.")
    logger.error("This is an error message.")
    logger.critical("This is a critical message.")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

posted @ 2024-01-04 16:49  txwtech  阅读(69)  评论(0编辑  收藏  举报