Print with line and file information

Updated Gribouillis 5 Tallied Votes 869 Views Share

This snippet defines a function printat() which adds line and file information to the normal print() function output. The intended use is a quick and dirty debugging information for everyday's use. A more complete solution is to use a logging/debugging/tracing framework.

#!/usr/bin/env python
# -*-coding: utf8-*-
# Module: printat (python 2 and 3)
# Author: Gribouillis for the python forum at www.daniweb.com
# Date: 2014 June 02
# License: Public Domain
# Use this code freely

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
__version__ = "0.0.3"
import sys


def this_line(level = 0):
    """return a pair (lineno, filename) where this function is called

    If level > 0, go back up to that level in the calling stack.
    
    The filename is the name in python's co_filename member
    of code objects.
    """
    frame = sys._getframe(level + 1)
    try:
        lineno = frame.f_lineno
        filename = frame.f_code.co_filename
        return (lineno, filename)
    finally:
        del frame

def printat(*args, **kwargs):
    """Print function with additional line number and filename information.
    
    Adds a string such as "at line 31 in foo.py" to the printed output,
    to indicate the position where the printat() function was called.

    All the calls to print() in a program can be changed
    to provide additional information by adding
    
        print = printat
        
    at the top of the program.
    """
    lineno, filename = this_line(1)
    args += ('at line {n} in {f}'.format(n=lineno, f=filename),)
    print(*args, **kwargs)
    
if __name__ == '__main__':
    printat("Hello World!")

""" my output -->
$ python printat.py
Hello World! at line 49 in printat.py
"""

I like this. I modified it so the function name would be included with frame.f_code.co_name.

Gribouillis 1,391 Programming Explorer Team Colleague

I like this. I modified it so the function name would be included with frame.f_code.co_name.

Yes it is tempting to do so. In exceptions tracebacks, the function name is given together with file name and line number. Another idea is to print only the file's basename (using os.path.basename()).

Gribouillis 1,391 Programming Explorer Team Colleague

Uploaded version 0.0.3 (uses sys._getframe() instead of inspect.currentframe())

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.