Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
my debug toys
#1
my debug toys: you can also download from http://ipal.net/free/debugtoys.py

#=======#=======#=======#=======#=======#=======#=======#=======#======
# -*- coding: utf-8 -*-
from __future__ import division, print_function, with_statement
# the above line is there in case Python2 is used.
from os import environ
#=======#=======#=======#=======#=======#=======#=======#=======#======
# these debug functions are enabled if the nvironment variable named
# 'godebug' (lower case) has a numeric value that is True.
#-------#-------#-------#-------#-------#-------#-------#-------#------
# the following functions, if enabled, are defined to do the actions
# described below, or if disabled, are defined to do nothing.
#-------#-------#-------#-------#-------#-------#-------#-------#------
#   pf()    like pr() below, but with arg1.format(arg2,arg3,...)
#   pr()    do printing just like print() then flush the file it used.
#   pv()    print variables, given their names, or report if undefined.
#   sl()    sleep a specified time after flushing stdout or file= file.
#=======#=======#=======#=======#=======#=======#=======#=======#======
try:
    godebug=eval(environ['godebug'])
except:
    godebug=0

if godebug:
    from sys import stderr, stdout

    # flush multiple files
    def _flush(*a):
        stderr.flush()
        stdout.flush()
        for f in a:
            f.flush()
        return

    # like pr() but with formatting
    def pf(fs,*args,**opts):
        opts['file'] = opts.get('file',stderr)
        if opts.get('file',None)!=stdout:
            _flush()
        try:
            print(fs.format(*args),**opts)
            _flush(opts['file'])
        except BrokenPipeError:
            pass
        return

    # do printing just like print() then flush the file it used
    def pr(*args,**opts):
        opts['file'] = opts.get('file',stderr)
        if opts.get('file',None)!=stdout:
            _flush()
        try:
            print(*args,**opts)
            _flush(opts['file'])
        except BrokenPipeError:
            pass
        return

    # print variables, given their names, or report if undefined
    def pv(*args,**opts):
        from inspect import currentframe
        opts['file'], c = opts.get('file',stderr), opts.pop('prefix','')
        try:
            if not args:
                print(**opts)
                _flush(opts['file'])
                return 0
            f = currentframe().f_back
            l, g = f.f_locals, f.f_globals
            q='line '+repr(f.f_lineno)+': '
            for name in args:
                _flush(opts['file'])
                s = name.split('.')
                n = s.pop(0)
                if n[:1] in '!$': # use what follows as a var name
                    n = n[1:]
                elif n[:1] in '=:': # use what follows as a prefix
                    c = n[1:]
                    continue
                elif n[:1] is '#': # use what follows as a comment
                    print(q+c+'............. ',
                          n[1:],
                          **opts)
                    continue
                elif not n: # null variable name
                    print(q+c+'............. ',
                          s[0],
                          **opts)
                    _flush(opts['file'])
                    continue
                elif n in l: # var is local
                    o, v = q+c+'... local var:', l[n]
                elif n in g: # var is global
                    o, v = q+c+'.. global var:', g[n]
                else: # not local or global
                    print(q+c+'............. ',
                          str(name),
                          'not assigned in local or global namespace',
                          **opts)
                    _flush(opts['file'])
                    continue
                while s:
                    m = s.pop(0)
                    if m in dir(v):
                        v, n = getattr(v,m), n + '.' + m
                    else:
                        break
                if isinstance(v,str) and len(v)<11:
                    x=['['+hex(ord(x)+256)[-2:]+']' for x in v]
                    print(o,repr(n),'=',repr(v),' '.join(x),**opts)
                else:
                    print(o,repr(n),'=',repr(v),**opts)
                _flush(opts['file'])
                continue
        except BrokenPipeError:
            pass
        return

    # sleep a specified time after flushing standard files
    def sl(sec,**opts):
        from time import sleep
        opts.get('file',stdout).flush()
        _flush()
        sleep(float(sec))
        return

    pr('environment variable "godebug" is',
       repr(godebug),
       'so debug functions are defined')

else:
    def pf(*a,**o): return # define the "do nothing" version of pf()
    def pr(*a,**o): return # define the "do nothing" version of pr()
    def pv(*a,**o): return # define the "do nothing" version of pv()
    def sl(*a,**o): return # define the "do nothing" version of sl()

#=======#=======#=======#=======#=======#=======#=======#=======#======
to use this, do from debugtoys import pf,pr,pv,sl and put some calls to pv() scattered around in your code. pass it arguments with strings naming your variables (even global ones). set environment variable godebug to a true numeric value and run you script.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Show Name of Calling function - Debug aid Larz60+ 0 1,973 Aug-11-2018, 02:54 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020