finding the file of a module from inside a class

Thomas Weholt thomas at gatsoft.no
Tue Sep 25 06:27:48 EDT 2001


"Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message
news:Xns91276D78CAF2Dduncanrcpcouk at 127.0.0.1...
> "Thomas Weholt" <thomas at gatsoft.no> wrote in
> news:YGXr7.371$n5b.170335232 at news.telia.no:
>
> > say I got a module test.py with this content:
> >
> > class MyClass:
> >     def __init__(self):
> >         pass
> >     def myfile(self):
> >         return '' # ????
>     return os.path.abspath(__file__)
> >
> > if I put this into a folder, ex. /home/thomas/dev/test/, how can I get
> > information about what file the code instance actually is stored in,
> > from inside my class? I want the myfile-method to return
> > /home/thomas/dev/test/test.py ( if the class is stored in a module
> > called test.py in a folder /home/thomas/dev/test/ of course ).
>
> __file__ should give you what you need. It may give you a relative path,
> but you can use os.path.abspath() to make it absolute.
>
> --
> Duncan Booth                                             duncan at rcp.co.uk
> int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
> "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

Tried this code :

import os

class MyClass:
    def __init__(self): pass
    def myfile(self): return os.path.abspath(__file__)

if __name__ == '__main__':
    x = MyClass()
    print x.myfile()

With this result :

Traceback (most recent call last):
  File "c:\python21\pythonwin\pywin\framework\scriptutils.py", line 298, in
RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "c:\python21\pythonwin\pywin\debugger\__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "c:\python21\pythonwin\pywin\debugger\debugger.py", line 582, in run
    _doexec(cmd, globals, locals)
  File "c:\python21\pythonwin\pywin\debugger\debugger.py", line 924, in
_doexec
    exec cmd in globals, locals
  File "C:\Temp\Script10.py", line 9, in ?
    print x.myfile()
  File "C:\Temp\Script10.py", line 5, in myfile
    def myfile(self): return os.path.abspath(__file__)
NameError: global name '__file__' is not defined
>>>

Hm ... if it was that simple it would be too good to be true.







More information about the Python-list mailing list