Skip to main content
 首页 » 编程设计

python之在 Python 中启用和禁用调试消息

2025年05月04日12三少

我目前正在学习 Python,为了了解幕后发生的事情,我写了很多打印输出。 鉴于返回并评论所有消息非常麻烦,我开始编写一个模块,在该模块中,我将所有消息设置为我想要使用它们的方法,然后使用 bool 值来关闭和打开消息。 问题是,我得到 None 打印输出而不是我的调试消息,这不是很优雅。有什么办法可以解决这个问题?

一些示例代码:

def setDebug(bool): 
    ''' 
    Toggles the debug messages 
    ''' 
 
    global _debug 
    _debug = bool 
 
 
def setNewMsg(msg): 
    ''' 
    Appends a new debug message to the list 
    ''' 
    global _debugMsg 
    _debugMsg.append(msg) 
 
def getDebugMsg(index): 
    ''' 
    Takes an int for a parameter and returns the debug message needed 
    ''' 
    global _debug 
    global _debugMsg 
 
    if _debug == True: 
        return _debugMsg[index]  
    else:  
        return 

请您参考如下方法:

既然你说你是 Python 新手,我认为你应该考虑使用 logging 模块

看看这个link ,也是 HOWTO真的很有帮助。

来自 Python 文档:

This module defines functions and classes which implement a flexible event logging system for applications and libraries. 

您可以设置日志记录模块以将所有打印件保存到文件中,并且通过控制日志记录级别,您可以控制消息的级别。

例子:

import logging 
logging.basicConfig(filename='mylog.log',level=logging.DEBUG) 
logging.debug('This message should go to the log file') 
logging.info('So should this') 
logging.warning('And this, too') 

如果 level=logging.DEBUG 您将能够看到所有消息,但通过更改为 level=logging.INFO 它将仅保存信息和多于。尝试链接,它们非常有用。