我想调试一个python程序,比如calibre。通常情况下,我使用pdb从控制台进行调试,但是当我将pdb与python GUI程序一起使用时,GUI部分(画布或见鬼的东西)冻结,并且以这种方式进行调试真的非常困难。
对于调试python GUI程序有什么建议吗?你是怎么做到的?我会在我的GUI代码中代表"用户操作"的每个事件处理程序函数/方法的顶部放置对logging.debug
的调用,即鼠标点击,进入键。此外,任何更新视图的高级函数都将在开始时调用logging.debug
。这些日志消息将报告函数/方法中使用的任何重要信息。因为消息是在DEBUG
级别记录的,所以您可以通过简单的配置更改来打开/关闭它们。
或者,虽然不复杂,但甚至忘记logging
模块并暂时放入print
语句可能更快,直到您找到问题。
下面是我写的一些代码,用一个旋转日志文件初始化logging
模块:
import pytz
timestamp_detailed_format = '%Y-%m-%d %H:%M:%S.%f %Z'
def detailed_format(date):
u"Given a datetime object return a detailed representation including fractional seconds and time zone"
return unicode(date.strftime(timestamp_detailed_format))
def localize_epoch_time(epoch_time, timezone=pytz.UTC):
u"Given an epoch time return an accurate, timezone-aware datetime object"
t = localtime(epoch_time)
epochdt = datetime(*(t[:6] + (int((epoch_time - long(epoch_time)) * 1000000),))).astimezone(timezone)
if hasattr(timezone, 'normalize'): # pytz tzinfo objects have this
return timezone.normalize(epochdt)
else: # tzinfo object not from pytz module
return epochdt
class TimezoneAwareFormatter(logging.Formatter):
u"custom log formatter using timezone-aware timestamps"
def __init__(self, logformat=None, timezone=pytz.UTC):
logging.Formatter.__init__(self, logformat)
self._timezone = timezone
def formatTime(self, record, _=None):
u"times will be formatted as YYYY-MM-DD HH:MM:SS.ssssss TZ"
return detailed_format(localize_epoch_time(record.created, self._timezone))
def simple_log_file(filename, logname=None, level=logging.NOTSET,
threshold=10485760, generations=2, quiet=False, timezone=pytz.UTC):
u"initialize logging API for a simple generational log file, return logger object"
formatter = TimezoneAwareFormatter('%(asctime)s %(levelname)s %(message)s', timezone)
handler = logging.handlers.RotatingFileHandler(filename, 'a', threshold, generations, 'UTF-8')
handler.setFormatter(formatter)
logger = logging.getLogger(logname)
logger.addHandler(handler)
logger.setLevel(level)
if not quiet: logger.info(u'Logging to this destination has started')
return logger