Import and absolute file names, sys.path including ''... or not
Jean-Michel Pichavant
jeanmichel at sequans.com
Tue May 19 13:28:42 EDT 2009
Hi fellows,
I spent quite a time on a malicious issue. I found out that there is a
slight difference on the sys.path content when either executing code
from a shell or from within a script.
This difference is the '' item, which is present in the shell form of
sys.path.
For instance, let's write this code in test.py:
import sys
print sys.path
shell form:
python
Python 2.4.4 (#2, Oct 22 2008, 19:52:44)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
['', other misc stuff] <- sys.path
script form:
python test.py
[other misc stuff] <- sys.path
The '' item is not here.
Problem is, '' is required for absolute path to be properly resolved. In
my code I sometimes have to import file in that way :
__import__('/some/absolute/path')
So the immediate solution is to write this:
if '' not in sys.path:
sys.path.append('') # make sure absolute path are properly resolved
in any case
I'm not a big fan of manipulating sys.path at the begining of my files.
Is there something I'm doing wrong ? Is there a standard/nice way to
support absolute path ? I guess '' is in fact aimed at resolving
relative path from the execution directory...
best regards,
Jean-Michel
More information about the Python-list
mailing list