Put Line Numbers in Python print() Output

If you have more than a hundred lines in your Python script, remembering where in the flow any particular print output comes from can cause you pause. I felt like having the line number from my code would help me more quickly and easily recognize the output.

I googled to see if it was possible, and found a few ways to do it. This way seemed really simple, and works great. It's especially easy because I nearly always import the 'sys' module in my work. This solution came from this stackoverflow post. While not the most popular answer to the issue, I thought this answer was the best one.

You can name the function whatever you want. I chose PPRINT().

Image: The function itself.

Image: An example of PPRINT use in my code.

Image: Here's the output in my console.

In this instance, I chose to split the output on two lines using the '\n' right before "Export Folder" in my PPRINT statement. You can, of course, keep all the output on a single line by not doing that.

Now I have a choice between using the normal 'print()' function or using this 'PPRINT()' function. It's very handy, and definitely a "Thing That Works."

Here's the function in text for copy/pasting:

import sys

def PPRINT(msg = None):
    print(f"Line No: {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")

As you might guess, I think PPRINT is another thing that works!

link to home page

Prev: Python - now you're talkin' Next: XMerge v1.4.0 Released

links

-->