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

hac*_*cke 1 python debugging nonetype

我目前正在学习Python,并且知道幕后发生了什么,我写了很多打印输出.看到回去评论我开始编写模块的所有消息都是一件大惊小怪的事情,我在方法中设置了我想要使用它们的所有消息,然后使用布尔值来关闭和打开消息.问题是,我得到无打印输出而不是我的调试消息,这不是很优雅.有办法解决这个问题吗?

一些示例代码:

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
Run Code Online (Sandbox Code Playgroud)

Kob*_*i K 8

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

看看这个链接,HOWTO也可以提供帮助.

来自Python文档:

This module defines functions and classes which implement a flexible event logging system for applications and libraries.
Run Code Online (Sandbox Code Playgroud)

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

例:

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')
Run Code Online (Sandbox Code Playgroud)

如果level=logging.DEBUG您能够看到所有消息,但通过更改level=logging.INFO它将只保存文件信息及以上信息.尝试他们非常有用的链接.