I’d like to make a switch from Windows to Linux (Ubuntu) writing my python programs but I just can’t get things to work. Here’s the problem: I can see that there are quite the number of modules pre-installed (like numpy, pandas, matplotlib, etc.) in Ubuntu. They sit nicely in the /host/Python27/Lib/site-packages directory. But when I write a test python script and try to execute it, it gives me an ImportError whenever I try to import a module (for instance import numpy as np
gives me ImportError: No module named numpy
). When I type which python
in the commandline I get the /usr/bin/python
path. I think I might need to change things related to the python path, but I don’t know how to do that.
Advertisement
Answer
You can use the following command in your terminal to see what folders are in your PYTHONPATH
.
python -c "import sys, pprint; pprint.pprint(sys.path)"
I’m guessing /host/Python27/Lib/site-packages
wont be in there (it doesn’t sound like a normal python path. How did you install these packages?).
If you want to add folders to your PYTHONPATH
then use the following:
export PYTHONPATH=$PYTHONPATH:/host/Python27/Lib/site-packages
Personally here are some recommendations for developing with Python:
Use
virtualenv
. It is a very powerful tool that creates sandboxed python environments so you can install modules and keep them separate from the main interpreter.Use
pip
– When you’ve created avirtualenv
, and activated it you can usepip install
to install packages for you. e.g.pip install numpy
will install numpy into your virtual environment and will be accessible from only this virtualenv. This means you can also install different versions for testing etc. Very powerful. I would recommend usingpip
to install your python packages over using ubuntuapt-get install
as you are more likely to get the newer versions of modules (apt-get
relies on someone packaging the latest versions of your python libraries and may not be available for as many libraries aspip
).When writing python scripts that you will make executable (
chmod +x my_python_script.py
) make sure you put#!/usr/bin/env python
at the top as this will pick up the python interpreter in your virtual environment. If you don’t (and put#!/usr/bin/python
) then running./my_python_script.py
will always use the system python interpreter.