如何调试 pythonic GUI 程序?

发布于 2024-11-24 05:40:42 字数 287 浏览 1 评论 0原文

我想调试一个Pythonic程序,例如calibre。通常,我使用 pdb 从控制台进行调试,但是当我将 pdb 与 pythonic 一起使用时GUI 程序,GUI 部分(画布或到底是什么)冻结,并且以这种方式调试真的非常困难。

对于调试 pythonic GUI 程序有什么建议吗?你怎么做?

I want to debug a pythonic program, such as calibre. Normally, I was using pdb to debug from the console, but when I use pdb with pythonic GUI programs, the GUI part (canvas or what the heck it is) freezes and it's really very hard to debug in that way.

Any suggestions for debugging pythonic GUI programs? How do you do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一萌ing 2024-12-01 05:40:42

我会在 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

I would place calls to logging.debug at the top of each event handler function/method in my GUI code that represents a "user action", i.e. mouse clicks, enter key. Also any high-level function that updates the view would have a logging.debug call at the beginning. These log messages would report any important information used in the function/method. Because the messages are logged at DEBUG level, you can turn them on/off with a simple configuration change.

Alternatively, while unsophisticated, it might be faster to forget even the logging module and put in print statements temporarily until you find the problem.

Here's some code I wrote to initialize the logging module with a rotating log file:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文