Archive for December, 2012
Where are those Print statements?
December 9th, 2012
When I'm debugging Python I tend to sprinkle my code liberally with print statements. Trouble is, I forget which files I added those print statements to and have to waste a few minutes tracking them down. Time which could be better spent doing pretty much anything else.
Not sure why I didn't think of this before, but I hacked together something that automatically prints the file and line of the print statement next to the output.
Here's the code:
import inspect import sys import os class DebugPrint(object): def __init__(self, f): self.f = f def write(self, text): frame = inspect.currentframe() filename = frame.f_back.f_code.co_filename.rsplit(os.sep, 1)[-1] lineno = frame.f_back.f_lineno prefix = "[%s:%s] " % (filename, lineno) if text == os.linesep: self.f.write(text) else: self.f.write(prefix + text) if not isinstance(sys.stdout, DebugPrint): sys.stdout = DebugPrint(sys.stdout)
To use it, save it as ‘debugprint.py’ then imported it somewhere. That's all you need to do. Works on Python 2.7 and probably other 2.X Pythons.
Here's what happens if you do it from the console:
>>> import debugprint >>> print "Hello" [<stdin>:1] Hello
For print statements in your app, you will get something like:
[foo.py:22] Hello
Search for Posts
2009
-
4 posts
-
2 posts
-
2 posts
-
1 post
-
6 posts
-
1 post
-
1 post
-
3 posts
-
11 posts
-
6 posts
-
4 posts
2008
-
1 post
-
1 post
-
1 post
-
5 posts
-
5 posts
-
1 post
-
6 posts
-
1 post
-
9 posts
-
2 posts
2007
-
4 posts
-
3 posts
-
14 posts
-
3 posts
-
7 posts
-
7 posts
-
16 posts
-
8 posts
-
2 posts
-
1 post