[Python-de] magischen Konstanten in Python?
Stefan Schwarzer
sschwarzer at sschwarzer.net
Fr Jan 2 10:20:44 CET 2009
Hallo Mathias,
On 2008-12-30 00:52, Mathias Uebel wrote:
> in PHP gibt es die sogenannten "magischen Konstanten", wie __FILE__,
> __LINE__ etc. Ich habe das immer gern zum Debuggen genutzt. Gibt es so
> etwa auch in Python?
außer dem von Marek genannten __name__ gibt es auch noch
__file__, das aber tatsächlich nur in Dateien definiert ist.
Falls ein Modul schon einmal in Bytecode übersetzt wurde, kann
__file__ aber auch eine .pyc-Datei bezeichnen:
>>> import os
>>> os.__file__
'/usr/lib/python2.5/os.pyc'
Mit dem traceback-Modul [1] kommt man (auch unabhängig von einer
vorher aufgetretenen Exception) an diverse Infos des
Aufruf-Stacks. Zum Beispiel liefert die Datei
-----
import pprint
import traceback
def f(unused):
print "Stack:"
traceback.print_stack()
print
print "The same information in another form:"
stack = traceback.extract_stack()
for file, line_number, function, call in stack:
print "In file %s, %s, line %d, called %s" % \
(file, function, line_number, call)
def g():
f("unused")
g()
-----
die Ausgabe
-----
Stack:
File "tb_test.py", line 19, in <module>
g()
File "tb_test.py", line 16, in g
f("unused")
File "tb_test.py", line 7, in f
traceback.print_stack()
The same information in another form:
In file tb_test.py, <module>, line 19, called g()
In file tb_test.py, g, line 16, called f("unused")
In file tb_test.py, f, line 10, called stack = traceback.extract_stack()
-----
Vielleicht ist auch noch das Modul inspect [2] interessant für
dich. Hier sind noch einige andere besondere Variablen
aufgelistet.
[1] http://docs.python.org/library/traceback.html#module-traceback
[2] http://docs.python.org/library/inspect.html#module-inspect
Viele Grüße
Stefan
Mehr Informationen über die Mailingliste python-de