Python equivalent of __LINE__ macro?
Jason Orendorff
jason at jorendorff.com
Tue Jan 8 13:32:56 EST 2002
David Brady wrote:
> As for Python, I was basically doing some stuff where
> I just wanted to print something like "Hey, this bit
> of script is buggy!" but I didn't want to hardcode the
> line number, because I kept added code above it,
> pushing it down the file.
Oh! The code I gave you before is for catching fatal
errors. It lets you put a try/except block in just one
place - around the main() of your script. Then it will
report any fatal errors in your code. You do not catch
each individual error at its source; the line number that
it spits out indicates where the error *occurred*, not
where the error gets *reported*.
I thought that was what you were asking for; but it
seems you are looking for the warnings module.
http://www.python.org/doc/current/lib/module-warnings.html
You can adapt it to Visual Studio like this:
import warnings
from warnings import warn
def my_formatwarning(message, category, filename, lineno):
return "%s(%i) : warning: %s" % (filename, lineno, message)
# Replace default warning formatter with custom formatter
warnings.formatwarning = my_formatwarning
Then use warn("parrot is dead") to send messages to stderr.
(Any python libraries that use warnings.warn() will also
generate VS-style messages, in this case.)
One last note: warn() ignores duplicate warnings by default.
If 2000 identical warnings are generated, you only get
one message. This is usually a good thing. To report
all warnings, do warnings.filterwarnings("always").
One really really last note: if you just want something
like __LINE__, here it is:
import inspect
def line():
return inspect.getouterframes(inspect.currentframe())[1][2]
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list