Reputation: 3433
Let's say I have a local development directory with modules that I'm writing, and a system-wide site-packages directory where these modules will eventually be installed. In the case where I'm modifying an existing module and I want to test it I would like to be sure that the module I'm importing is the one in my local site-packages directory. Reading about the site module it seems like I can have a file with a .pth
suffix where each line in that file will be appended to the sys.path
variable. I've set that up, and I can confirm that my development directory is showing up later in the list, but when I import a module it's importing from the system wide directory.
Simplified Example:
$ virtualenv test_sys
$ cd test_sys
$ source bin/activate
$ mkdir site_modules
$ mkdir user_modules
In each site_modules and user_modules I've put a directory called test_module
with the following in the __init__.py
:
import os
print(os.path.abspath(__file__))
Now I've added a file called site_modules.pth
to test_sys/lib/python2.7/site-packages
:
/home/chris/test_sys/site_modules
/home/chris/test_sys/user_modules
And I expect that when I import test_module from the python interpreter it would print the user_modules
directory but it doesn't:
>>> import test_module
/home/chris/test_sys/site_modules/test_module/__init__.pyc
>>>
Yes, I've ensured that user_modules
shows up later in sys.path
than site_modules
.
How can I ensure that a module that exists in multiple directories in sys.path
will always be imported from a specific directory?
Upvotes: 0
Views: 131
Reputation: 213688
Python's sys.path
does work mostly like the Unix PATH
environment variable. Both of them use the first object they find in the path. So if you want to have user_modules
override site_modules
, you have to put it first, not second:
/home/chris/test_sys/user_modules /home/chris/test_sys/site_modules
This is the same as Unix PATH
PATH=/usr/local/bin:/usr/bin:/bin
Which means that local packages (ones not installed by the package manager) from /usr/local
will override system packages in /usr
.
Upvotes: 1