I installed Python3.4.3 in my home directory so it is under /home/jdoe/.local/bin/python3
and I pip installed some external modules to this by doing pip install --user package_name
. However now when writing my python script the package python looks for is not found because it is looking in the usr/lib
but the package is not there. How can I import a module so python looks at the site-packages installed in my personal home directory?
Append the path to your path variable
import sys
sys.path.append("<path>")
However are you sure that your pip install --user
actually installed a python3.4 package, usually one does not need to add any paths to the path for pip installed packages?
What is the output of pip --version
As explained in this tutorial , there are basically 2 options: use PYTHONPATH
or sys.append
.
PYTHONPATH
is an environment variable used to extend the directories where Python searches for modules. It can be set in the command line before running python:
$ export PYTHONPATH=$PYTHONPATH:<Path to Module>
$ python
Or adding the line export PYTHONPATH=$PYTHONPATH:<Path to Module>
in the bash configuration file (ie .bashrc
). If it is set in the .bashrc
, then all python scripts executed in the computer will search for modules there.
sys.append
is called from within Python. And it can be added at the beginning of a file that calls the module or called from the Python interpreter with the following lines:
import sys
sys.path.append('<Path to Module>')
Let's say I have a script that falls under $HOME/repo/code/sample.py
and I want to import it into $HOME/repo2/code/sample.py
one way to do it is:
import os
import sys
env=os.path.expanduser(os.path.expandvars($HOME/repo) # "source" directory with python script
sys.path.insert(0, env)
import code.sample
This will remove the dependency to export PYTHONPATH
, and allow you to easily import between files/folders as if they are any other module.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.