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.

Edited 2 Years Ago by Gribouillis

#!/usr/bin/env python
# -*-coding: utf8-*-
# Module: printat (python 2 and 3)
# Author: Gribouillis for the python forum at
# 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)
        lineno = frame.f_lineno
        filename = frame.f_code.co_filename
        return (lineno, filename)
        del frame

def printat(*args, **kwargs):
    """Print function with additional line number and filename information.
    Adds a string such as "at line 31 in" 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
Hello World! at line 49 in

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

Edited 2 Years Ago by chriswelborn: grammar

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()).

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

Edited 2 Years Ago by Gribouillis

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.