python-命令行,参数解析,日志管理框架(cmd,argparse,logging模块)_def __init__(self,log_dir_name) self

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

框架结构

  • lady_killer.py 调用cli
  • cli.py 继承Cmd模块,使用argparse模块进行参数解析,调用hello进行测试
  • hello.py 一些简单的输出,调用log进行日志模块的测试
  • log.py  继承logging模块,进行日志管理
  • constans.py 常量,也可理解为配置文件

代码

lady_killer.py

"""
--coding:utf-8--
@File: lady_killer.py
@Author:frank yu
@DateTime: 2020.08.19 15:38
@Contact: frankyu112058@gmail.com
@Description:main file
"""
from cli import Cli


def start():
    cli = Cli()
    cli.cmdloop()


def main():
    start()


if __name__ == "__main__":
    main()

cli.py

"""
--coding:utf-8--
@File: cli.py
@Author:frank yu
@DateTime: 2020.08.19 15:46
@Contact: frankyu112058@gmail.com
@Description:module to combine and Cmd and argparse
"""
import argparse
import sys
from cmd import Cmd

from hello import Hello


class Cli(Cmd):
    def __init__(self):
        """
        function: __init__
        :return: None
        """
        title = \
            '''
        +++                +++++        ++++++++++++    ++++       ++++    
        +++               +++ +++       +++++++++++++      +++   +++
        +++              +++   +++      +++        +++        +++
        +++             +++++++++++     +++        +++        +++
        +++++++++++    +++       +++    +++++++++++++         +++
        +++++++++++   +++         +++   +++++++++++           +++
        
        Welcome to LADY, a Command and Logging Frame made by lady_killer9(https://blog.csdn.net/lady_killer9)
        version 1.0.0
        use hello -h/--help to show options
        Hit '<ctrl-c>' or 'exit' to shutdown LADY.
            '''
        display = "\033[1;36;40m{}\033[0m".format(title)
        self.do_clear(None)
        print(display)
        Cmd.__init__(self)
        self.prompt = 'lady_killer>'

    def emptyline(self):
        """
        Called when an empty line is entered in response to the prompt.
        If this method is not overridden, it repeats the last nonempty
        command entered.
        """
        return

    def do_hello(self, cmd):
        """
        function:run hello module to test program
        :param cmd: command from console
        :return: None
        """
        commond = cmd.split()
        # print(commond)
        parse = argparse.ArgumentParser(description='Process some integers.')
        parse.prog = "hello"
        parse.usage = parse.prog + " -l [-d] [-i] [-w] [-e] [-c]"
        parse.add_argument('-d', '--debug', type=str, default="this is debug message",
                           help="print message with logging.DEBUG")
        parse.add_argument('-i', '--info', type=str, default="this is info message",
                           help="print message with logging.INFO")
        parse.add_argument('-w', '--warning', type=str, default="this is warning message",
                           help="print message with logging.WARN")
        parse.add_argument('-e', '--error', type=str, default="this is error message",
                           help="print message with logging.ERROR")
        parse.add_argument('-c', '--critical', type=str, default="this is critical message",
                           help="print message with logging.CRITICAL")
        parse.add_argument('-l', type=str, choices=["debug", "info", "warn", "error", "critical"],
                           help="set log level(debug info warn error critical)")
        args = parse.parse_args(commond)
        # print(args)
        kwargs = dict()
        kwargs['d_info'] = args.debug
        kwargs['i_info'] = args.info
        kwargs['w_info'] = args.warning
        kwargs['e_info'] = args.error
        kwargs['c_info'] = args.critical
        kwargs['l'] = args.l
        hello = Hello()
        hello.set_log(**kwargs)
        hello.debug(**kwargs)
        hello.info(**kwargs)
        hello.warning(**kwargs)
        hello.error(**kwargs)
        hello.critical(**kwargs)

    def do_exit(self, msg):
        """
        function: close the cmd
        :param msg: param about service to stop
        :return: None
        """
        print('Bye!!!')
        sys.exit(0)

    def do_clear(self, msg):
        """
        function: clear screen
        """
        print("\033c")

继承Cmd模块,使用argparse模块进行参数解析(空格分隔),输出标题,添加exit,clear,hello三条命令,hello中添加部分参数

hello.py

"""
--coding:utf-8--
@File: hello.py
@Author:frank yu
@DateTime: 2020.08.19 16:02
@Contact: frankyu112058@gmail.com
@Description:this is module for test
"""
from log import *

log = Log()


class Hello:
    def __init__(self):
        pass

    def debug(self, **kwargs):
        info = kwargs.get('d_info')
        log.log_show_store(info, logging.DEBUG)

    def info(self, **kwargs):
        info = kwargs.get('i_info')
        log.log_show_store(info, logging.INFO)

    def warning(self, **kwargs):
        info = kwargs.get('w_info')
        log.log_show_store(info, logging.WARN)

    def error(self, **kwargs):
        info = kwargs.get('e_info')
        log.log_show_store(info, logging.ERROR)

    def critical(self, **kwargs):
        info = kwargs.get('c_info')
        log.log_show_store(info, logging.CRITICAL)

    def set_log(self, **kwargs):
        level = kwargs.get('l')
        # print(level)
        if level == "debug":
            log.logger.setLevel(logging.DEBUG)
        elif level == "info":
            log.logger.setLevel(logging.INFO)
        elif level == "warn":
            log.logger.setLevel(logging.WARN)
        elif level == "error":
            log.logger.setLevel(logging.ERROR)
        elif level == "critical":
            log.logger.setLevel(logging.CRITICAL)
        else:
            log.log_show("please input -l", logging.CRITICAL)
            exit(0)

log.py

"""
--coding:utf-8--
@File: log.py.py
@Author:frank yu
@DateTime: 2020.08.19 15:22
@Contact: frankyu112058@gmail.com
@Description:log module
"""
import logging
import os
import random
import sys
import threading
import time
from shutil import copyfile
from constants import *
from colorlog import ColoredFormatter


class Log:
    def __init__(self, log_dir=LOG_DIR):
        """
        function:init create log file, judge if log file is too bigger
        :param log_dir: directory of logs
        """
        log_path = log_dir + "/log"
        if not os.path.exists(log_dir):
            os.mkdir(log_dir)
            os.chmod(log_dir, 0o777)
        if not os.path.exists(log_path):
            f = open(log_path, mode='w', encoding='utf-8')
            f.close()
            os.chmod(log_path, 0o777)
        # if log file is more than 1MB, copy to a file and clear log file
        if os.path.getsize(log_path) / 1048576 > 1:
            print(os.path.getsize(log_path))
            copyfile(log_path, log_dir + "/log" + str(time.time()).replace(".", ""))
            with open(log_path, 'w') as f:
                f.truncate()
                f.close()
        self.logger_format = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
        self.c_logger_format = ColoredFormatter(fmt='%(log_color)s%(asctime)s' \
                                                    ' - %(log_color)s%(levelname)s: %(log_color)s%(message)s',
                                                reset=True,
                                                secondary_log_colors={},
                                                style='%'
                                                )
        self.logger = logging.getLogger(str(random.random()))
        self.logger.handlers.clear()
        self.logger.setLevel(logging.DEBUG)

        self.filehandler = logging.FileHandler(log_path, mode='a')
        self.filehandler.setLevel(logging.DEBUG)
        self.filehandler.setFormatter(self.logger_format)

        self.stdouthandler = logging.StreamHandler(sys.stdout)
        self.stdouthandler.setLevel(logging.DEBUG)
        self.stdouthandler.setFormatter(self.c_logger_format)

        self.logger.addHandler(self.stdouthandler)
        self.logger.addHandler(self.filehandler)

        self.__lock = threading.Lock()

    def log_show_store(self, msg, level):
        """
        function: show logs on screen and store logs
        to log file

        :param msg:message of log
        :param level:level of log

        return: None
        """
        self.__lock.acquire()
        self.logger.addHandler(self.stdouthandler)
        self.logger.addHandler(self.filehandler)
        self.__log(msg=msg, level=level)
        self.__lock.release()

    def __log(self, msg=None, level=logging.INFO):
        if level == logging.DEBUG:
            self.logger.debug(msg)
        elif level == logging.INFO:
            self.logger.info(msg)
        elif level == logging.WARNING:
            self.logger.warning(msg)
        elif level == logging.ERROR:
            self.logger.error(msg)
        elif level == logging.CRITICAL:
            self.logger.critical(msg)

    def log_show(self, msg, level):
        """
        function:show msg on the screen
        :param msg:message of log
        :param level: level of log
        """
        self.__lock.acquire()
        self.logger.removeHandler(self.filehandler)
        self.logger.addHandler(self.stdouthandler)
        self.__log(msg, level=level)
        self.logger.removeHandler(self.stdouthandler)
        self.logger.addHandler(self.filehandler)
        self.__lock.release()

(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值