__LINE__ and __FILE__ functionality in Python?

Maric Michaud maric at aristote.info
Sun Aug 13 07:56:24 EDT 2006


Le dimanche 13 août 2006 13:31, Joakim Hove a écrit :
> Hello,
>
> i have simple[1] function like this:
>
>    def log_msg(msg , file , line):
>        print "%s:%s   %s" % (file,line,msg)
>
> the file and line arguments should be the filename and linenumber of
> the source file where the function is called. If this were C I would
> have used the __FILE__ and __LINE__ macros as:
>
>   log_msg(msg , __FILE__ , __LINE__)
>
> Is there a way to emulate this behaviour in Python?

Sure, try :

In [46]: import inspect

In [47]: c=inspect.currentframe()

In [48]: c.f_lineno
Out[48]: 1

In [49]: c.f_code.co_filename
Out[49]: '<ipython console>'

Of course, in the console, these are not truly relevant.


-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list