我想调试pythonic程序,例如calibre。通常情况下,我使用pdb来从控制台进行调试,但是当我使用pdb和pythonic GUI程序时,GUI部分(画布或它的内容)会冻结,并且以这种方式调试真的非常困难。
有关调试pythonic GUI程序的任何建议吗?你是怎么做到的?
答案 0 :(得分:0)
我会在我的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