温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python调试的方法是什么

发布时间:2022-10-12 17:27:34 来源:亿速云 阅读:121 作者:iii 栏目:web开发

这篇文章主要介绍“Python调试的方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python调试的方法是什么”文章能帮助大家解决问题。

记录是必须的

如果你编写应用程序时没有某种日志设置,你最终会后悔。如果应用程序中没有任何日志,则很难排除任何错误。幸运的是,在Python中,设置基本日志记录器非常简单:

import logging
logging.basicConfig(
    filename='application.log',
    level=logging.WARNING,
    format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
    datefmt='%H:%M:%S'
)

logging.error("Some serious error occurred.")
logging.warning('Function you are using is deprecated.')

这就是开始将日志写入文件所需的全部内容,该文件将如下所示(你可以使用logging.getLoggerClass().root.handlers[0].baseFilename查找文件路径):

[12:52:35] {<stdin>:1} ERROR - Some serious error occurred.
[12:52:35] {<stdin>:1} WARNING - Function you are using is deprecated.

这种设置似乎已经足够好了(通常情况下也是如此),但配置良好、格式化良好、可读的日志可以让你的生活更轻松。改进和扩展配置的一种方法是使用日志记录器读取的.ini.yaml文件。例如,你可以在配置中执行以下操作:

version: 1
disable_existing_loggers: true

formatters:
  standard:
    format: "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
    datefmt: '%H:%M:%S'

handlers:
  console:  # handler which will log into stdout
    class: logging.StreamHandler
    level: DEBUG
    formatter: standard  # Use formatter defined above
    stream: ext://sys.stdout
  file:  # handler which will log into file
    class: logging.handlers.RotatingFileHandler
    level: WARNING
    formatter: standard  # Use formatter defined above
    filename: /tmp/warnings.log
    maxBytes: 10485760 # 10MB
    backupCount: 10
    encoding: utf8

root:  # Loggers are organized in hierarchy - this is the root logger config
  level: ERROR
  handlers: [console, file]  # Attaches both handler defined above

loggers:  # Defines descendants of root logger
  mymodule:  # Logger for "mymodule"
    level: INFO
    handlers: [file]  # Will only use "file" handler defined above
    propagate: no  # Will not propagate logs to "root" logger

在python代码中拥有这种广泛的配置将很难导航、编辑和维护。将内容保存在YAML文件中,可以更轻松地设置和调整多个日志记录程序,这些日志记录程序具有非常特定的设置,如上述设置。

如果你想知道所有这些配置字段的来源,这些都官方文档中记录,其中大多数只是关键字参数,如第一个示例所示。

因此,现在文件中有配置,意味着我们需要以某种方式加载。最简单的方法是使用YAML文件:

import yaml
from logging import config

with open("config.yaml", 'rt') as f:
    config_data = yaml.safe_load(f.read())
    config.dictConfig(config_data)

Python logger实际上并不直接支持YAML文件,但它支持字典配置,可以使用yaml.safe_load从YAML轻松创建字典配置。如果你倾向于使用旧的.ini文件,那么我只想指出,根据官方文档,使用字典配置是新应用程序的推荐方法。有关更多示例,请查看官方日志记录手册。

日志装饰器

继续前面的日志记录技巧,你可能会遇到需要记录一些错误函数调用的情况。你可以使用日志装饰器来代替修改所述函数的主体,该装饰器将使用特定的日志级别和可选消息记录每个函数调用。让我们看看装饰器:

from functools import wraps, partial
import logging

def attach_wrapper(obj, func=None):  # Helper function that attaches function as attribute of an object
    if func is None:
        return partial(attach_wrapper, obj)
    setattr(obj, func.__name__, func)
    return func

def log(level, message):  # Actual decorator
    def decorate(func):
        logger = logging.getLogger(func.__module__)  # Setup logger
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        log_message = f"{func.__name__} - {message}"

        @wraps(func)
        def wrapper(*args, **kwargs):  # Logs the message and before executing the decorated function
            logger.log(level, log_message)
            return func(*args, **kwargs)

        @attach_wrapper(wrapper)  # Attaches "set_level" to "wrapper" as attribute
        def set_level(new_level):  # Function that allows us to set log level
            nonlocal level
            level = new_level

        @attach_wrapper(wrapper)  # Attaches "set_message" to "wrapper" as attribute
        def set_message(new_message):  # Function that allows us to set message
            nonlocal log_message
            log_message = f"{func.__name__} - {new_message}"

        return wrapper
    return decorate

# Example Usage
@log(logging.WARN, "example-param")
def somefunc(args):
    return args

somefunc("some args")

somefunc.set_level(logging.CRITICAL)  # Change log level by accessing internal decorator function
somefunc.set_message("new-message")  # Change log message by accessing internal decorator function
somefunc("some args")

毋庸置疑,这可能需要一点时间才能让你的头脑清醒(你可能只想复制粘贴并使用它)。这里的想法是,log函数接受参数,并将其提供给内部wrapper函数。然后,通过添加附加到装饰器的访问器函数,使这些参数可调整。至于functools.wraps装饰器——若我们在这里不使用它,函数的名称( func.__name__)将被装饰器的名称覆盖。但这是个问题,因为我们想打印名字。这可以通过functools.wraps将函数名、文档字符串和参数列表复制到装饰器函数来解决。

无论如何,这是上面代码的输出。很整洁,对吧?

2020-05-01 14:42:10,289 - __main__ - WARNING - somefunc - example-param
2020-05-01 14:42:10,289 - __main__ - CRITICAL - somefunc - new-message

__repr__更多可读日志

对代码的简单改进使其更易于调试,就是在类中添加__repr__方法。若你不熟悉这个方法,它所做的只是返回类实例的字符串表示。使用__repr__方法的最佳实践是输出可用于重新创建实例的文本。例如:

class Circle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius

    def __repr__(self):
        return f"Rectangle({self.x}, {self.y}, {self.radius})"

...
c = Circle(100, 80, 30)
repr(c)
# Circle(100, 80, 30)

如果如上所示表示对象是不可取的或不可能的,那么好的替代方法是使用<...>表示,例如<_io.TextIOWrapper name='somefile.txt' mode='w' encoding='UTF-8'>

除了__repr__之外,实现__str__方法也是一个好主意,默认情况下,在调用print(instance)时使用该方法。使用这两种方法,只需打印变量即可获得大量信息。

__missing__字典的Dunder方法

如果你出于任何原因需要实现自定义字典类,那么当你尝试访问一些实际上不存在的键时,可能会因为KeyError而出现一些bug。为了避免不得不在代码中四处查看缺少的,可以实现特殊的__missing__方法,每次引发KeyError时都会调用该方法。

class MyDict(dict):
    def __missing__(self, key):
        message = f'{key} not present in the dictionary!'
        logging.warning(message)
        return message  # Or raise some error instead

上面的实现非常简单,只返回并记录带有丢失key的消息,但你也可以记录其他有价值的信息,以便为你提供有关代码中出现错误的更多上下文。

调试崩溃的应用程序

如果你的应用程序在你有机会看到其中发生了什么之前崩溃,你可能会发现这个技巧非常有用。

-i使用参数-i ( python3 -i app.py)运行应用程序会导致它在程序退出后立即启动交互式 shell。此时你可以检查变量和函数。

如果这还不够好,可以使用更大的hammer-pdb-Python调试器。pdb有相当多的特性,可以保证文章的独立性。但这里是一个例子和最重要的部分概要。让我们先看看我们的小崩溃脚本:

# crashing_app.py
SOME_VAR = 42

class SomeError(Exception):
    pass

def func():
    raise SomeError("Something went wrong...")

func()

现在,如果我们使用-i参数运行它,我们就有机会调试它:

# Run crashing application
~ $ python3 -i crashing_app.py
Traceback (most recent call last):
  File "crashing_app.py", line 9, in <module>
    func()
  File "crashing_app.py", line 7, in func
    raise SomeError("Something went wrong...")
__main__.SomeError: Something went wrong...
>>> # We are interactive shell
>>> import pdb
>>> pdb.pm()  # start Post-Mortem debugger
> .../crashing_app.py(7)func()
-> raise SomeError("Something went wrong...")
(Pdb) # Now we are in debugger and can poke around and run some commands:
(Pdb) p SOME_VAR  # Print value of variable
42
(Pdb) l  # List surrounding code we are working with
  2
  3   class SomeError(Exception):
  4       pass
  5
  6   def func():
  7  ->     raise SomeError("Something went wrong...")
  8
  9   func()
[EOF]
(Pdb)  # Continue debugging... set breakpoints, step through the code, etc.

上面的调试会话非常简单地展示了如何使用pdb。程序终止后,我们进入交互式调试会话。首先,我们导入pdb并启动调试器。此时,我们可以使用所有pdb命令。作为上面的示例,我们使用p命令打印变量,使用l命令打印列表代码。大多数情况下,你可能希望设置断点,你可以使用b LINE_NO来设置断点,并运行程序,直到达到断点(c),然后继续使用s单步执行函数,也可以使用w打印堆栈轨迹。有关命令的完整列表,你可以转到官方pdb文档。

检查堆栈轨迹

例如,假设你的代码是在远程服务器上运行的Flask或Django应用程序,你无法在其中获得交互式调试会话。在这种情况下,你可以使用tracebacksys包来了解代码中的错误:

import traceback
import sys

def func():
    try:
        raise SomeError("Something went wrong...")
    except:
        traceback.print_exc(file=sys.stderr)

运行时,上面的代码将打印引发的最后一个异常。除了打印例外,你还可以使用traceback包打印堆栈轨迹(traceback.print_stack())或提取原始堆栈帧,对其进行格式化并进一步检查(traceback.format_list(traceback.extract_stack()))。

在调试期间重新加载模块

有时,你可能正在调试或试验交互式shell中的某些函数,并对其进行频繁更改。为了使运行/测试和修改的循环更容易,你可以运行importlib.reload(module)以避免每次更改后重新启动交互会话:

>>> import func from module
>>> func()
"This is result..."

# Make some changes to "func"
>>> func()
"This is result..."  # Outdated result
>>> from importlib import reload; reload(module)  # Reload "module" after changes made to "func"
>>> func()
"New result..."

这个技巧更多的是关于效率而不是调试。能够跳过一些不必要的步骤,使你的工作流程更快、更高效,这总是很好的。通常,不时地重新加载模块是一个好主意,因为它可以帮助你避免调试同时已经修改过多次的代码。

关于“Python调试的方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI