On 4/3/06, Talin <[EMAIL PROTECTED]> wrote:
Thomas Wouters <thomas <at> python.org> writes:

> I'm not sure what you're missing. The __main__ module has __file__:

Except that they are not the same!

When I print __file__ from my __main__ module, I get the name of the
file only, no path.

You get the path that was used to run the file:

centurion:~ > python ~thomas/tmp.py
__file__: /home/thomas/tmp.py
__main__.__file__: /home/thomas/tmp.py
 
However, when I print __file__ from my imported module, I get the
complete, absolute path to the module.

Incorrect: you get the path that was used to import the module. If a relative path is in sys.path (like its first element usually is), the module's __file__ will be a relative path:

 centurion:~ > python -c 'import tmp'
__file__: tmp.py

In fact, if I do a "print dir()" for the main module and the imported
module, I get something like this:

main: ['__builtins__', '__file__', '__name__', '__pymate', 'input', 'raw_input']
imported: ['__builtins__', '__doc__', '__file__', '__name__',
                 '__path__', 'fnmatch', 'os']

Note that the impored module has a "__path__" attribute, while the
main module does not.

Only packages have a __path__ attribute. Try checking on a module that is a .py file. Likewise, not all modules have a __file__ attribute:

>>> posix.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute '__file__'

The reason I bring this up is that it is a common usage pattern for
a particular source file to be run as both a main and as an imported
module. Suppose you have a bunch of test data that is in a subdir
of your source file. You'd like to be able to have a single, uniform
way to locate your module's data, regardless if you are __main__
or not.

__file__ is it. os.path.abspath() it with os.getcwd().

--
Thomas Wouters < [EMAIL PROTECTED]>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to