Hello,

I use a data file that lies on disk in the same directory that the
module which makes use of it.

The data file is checked in the repository and gets installed by
the distutils ``package_data`` directive, so it is in place both
during development and after and install.

In my program, I need to find the absolute path to this data file.

I could think of 3 ways to do this:
1. using the __path__ property in the module
2. using __file__ property in the module
3. using __file__ and os.getcwd() in the module

The first option does not work, because __path__ is initialised after the
module is loaded (apparently).

Solution 2  works, but behaves differently when ran from python or
from a doctest file. The path in __file__ is absolute if the program
is ran directly by ``python``, and relative if it is ran by
``python -m doctest``.

Solution 3 works. However if there is a better way to do this, please let me
know.

I could not find anything documenting what the proper value for __file__
should be. Maybe my problem with solution 2 is a bug in doctest or runpy?

I put up a simple example exhibiting the problem.

Here are the results on my mac (using python from macport)
I get the same results using python 2.6, 2.7 and 3.1

$ python2.6 test.py
/Users/seb/Devel/arboris-python/src/pyfile
/Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
/Users/seb/Devel/arboris-python/src/pyfile
/Users/seb/Devel/arboris-python/src/pyfile

$ python2.6 -m doctest test.txt
**********************************************************************
File "test.txt", line 5, in test.txt
Failed example:
    print mod.__file__
Expected:
    /Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
Got:
    mod.pyc
**********************************************************************
File "test.txt", line 7, in test.txt
Failed example:
    print(mod.whereami)
Expected:
    /Users/seb/Devel/arboris-python/src/pyfile
Got:
    <BLANKLINE>
**********************************************************************
File "test.txt", line 9, in test.txt
Failed example:
    print(mod.whereami2)
Expected:
    /Users/seb/Devel/arboris-python/src/pyfile
Got:
    /Users/seb/Devel/arboris-python/src/pyfile/
**********************************************************************
1 items had failures:
   3 of   6 in test.txt
***Test Failed*** 3 failures.

Cheers
Sebastian
>>> import os
>>> print(os.getcwd())
/Users/seb/Devel/arboris-python/src/pyfile
>>> import mod
>>> print(mod.__file__)
/Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
>>> print(mod.whereami)
/Users/seb/Devel/arboris-python/src/pyfile
>>> print(mod.whereami2)
/Users/seb/Devel/arboris-python/src/pyfile

Attachment: mod.py
Description: Binary data

Attachment: test.py
Description: Binary data

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to