Advertisement

python 自己写个调试工具

阅读量:

python 自己写个调试工具

建议直接使用logging模块

代码

复制代码
    # -*- coding:utf-8 -*-
    import time
    import sys
    
    
    def get_now_time():
    """
    获取当前日期时间
    :return:当前日期时间
    """
    now = time.localtime()
    now_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
    # now_time = time.strftime("%Y-%m-%d ", now)
    return now_time
    
    
    def write_log(path, data):
    """
    像文件中写入内容,可追加
    :param path:文件路径
    :param data:写入内容
    :return:
    """
    now_time = get_now_time()
    with open(path, "a", encoding="utf-8") as file:  # 只需要将之前的”w"改为“a"即可,代表追加内容
        file.write(
            "时间:"
            + now_time
            # + "\n"
            + "  文件位置:"
            + __file__
            # + "\n"
            + "  行数:"
            + str(sys._getframe().f_lineno)
            + "\n"
            + "    "
            + data
            + "\n"
        )
    
    
    if __name__ == '__main__':
    write_log("debug.txt", '调试信息:'+'信息')
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-17/UgSXpeWvkcA6x3hqGC15IPfMOQLR.png)

把print写入txt

复制代码
    import sys
    
    
    class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a", encoding="utf-8")
    
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
    
    def flush(self):
        pass
    
    
    if __name__ == '__main__':
    sys.stdout = Logger('debug.txt')
    print("测试")
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-17/aNsTLYBtZnSgVAefUxdRCq2FiJw7.png)
复制代码
    def print2txt(output_path, input_data):
    """
    print数据到txt文件
    :param output_path:txt文件路径
    :param input_data:输入数据
    :return:
    """
    with open(output_path, 'a') as f:
        print(
            input_data,  # 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
            file=f,  # 要写入的文件对象。 文件打印到a.txt文件中
        )
    
    
    if __name__ == '__main__':
    print2txt("debug.txt", "hello world: python")
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-17/Ox8FG5L1Ebvrm4BoCcaQ3eyjntHD.png)

全部评论 (0)

还没有任何评论哟~