Importing Python modules on Linux from an NTFS share
My problem is a difference in how Python searches for modules on Windows/Linux.
I have a directory foo
on a Windows 7 machine (NTFS), which I mount in a Ubuntu 10.04 virtual guest running on the same machine (via VirtualBox' guest additions). Inside foo
, there is a file OS.py
(note the upper case) with the following content:
bar = 1
Here's the output of a Python (2.5.4) session on the host (Win 7) inside foo
:
>>> f = open('os.py') # Note the lower case
>>> f.readlines()
['bar = 1\n']
>>> f.close()
>>> import os
>>> dir(os)
(content of the Python standard os package)
And here's the output on the guest (Ubuntu), running Python 2.6.5 in foo
:
>>> f = open('os.py') # Note the lower case
>>> f.readlines()
['bar = 1\n']
>>> f.close()
>>> import os
>>> dir(os)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bar']
So on both platforms, Python loads the same file foo/OS.py
when using open('os.py')
, which is fine, since NTFS is case-insensitive. What I don't understand 开发者_StackOverflowis the different behaviour regarding import
. I would have expected that foo/OS.py
is imported on both platforms, or at least that the behaviour is the same.
Is there a reason for this inconsistency?
Note: ''
is the first entry in sys.path
on both platforms.
Your problem has nothing to do with Linux or NTFS, the behaviour is exactly the same in a pure Windows environment with any Windows file system NTFS or FAT: Windows regards filenames as case insensitive, but Python regards module names as case sensitive.
All that is happening here is that when Python searches for a module it does its own case-sensitive search so it never sees the lower case filename: it isn't blindly trying to open the file 'OS.py' in every folder on the Python path, it is searching each folder for files named 'OS' plus any of a number of possible extensions, that search on Windows might return files named 'os' but they are immediately filtered out and ignored.
If I remember correctly the exact behaviour has varied over time: very old versions of Python would ignore the case when importing modules on Windows, then it became a warning and now it simply ignores them.
For more information see http://www.python.org/dev/peps/pep-0235/ (but I don't know if it is entirely up to date).
If You want to find import your selfmade OS.py in linux enviroment, you can add path to foo/ dir in PYTHONPATH variable. Something like this: export PYTHONPATH=$PYTHONPATH:/PathToFoo. also you can run python interpreter like this: env PYTHONPATH=$PYTHONPATH:/PathToFoo python
精彩评论