finding the file of a module from inside a class

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Sep 25 09:27:49 EDT 2001


"Thomas Weholt" <thomas at gatsoft.no> wrote in
news:E_Yr7.373$n5b.170821632 at news.telia.no: 
> 
> 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.
> 
It is that simple. You said you had a module test.py, but your example is 
using a script not a module. The __file__ attribute is set for every 
module, but it isn't set for a script---sorry, I should have mentioned 
that. It also isn't set in a few other situations that shouldn't worry you 
(like builtin modules or using exec to build your module).

I believe that for a script, the first element on sys.path will be the 
directory from which the script is loaded (unless someone has modified 
sys.path).

-- 
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?



More information about the Python-list mailing list