Where should I put my own python module so that it can be imported

Solution 1:

I usually put the stuff i want to have ready to import in the user site directory:

~/.local/lib/pythonX.X/site-packages

To show the right directory for your platform, you can use python -m site --user-site


edit: it will show up in sys.path once you create it:

mkdir -p "`python -m site --user-site`"

Solution 2:

So if your a novice like myself and your directories are not very well organized you may want to try this method.

Open your python terminal. Import a module that you know works such as numpy in my case and do the following. Import numpy

numpy.__file__

which results in

'/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site- packages/numpy/__init__.py'

The result of numpy.__file__ is the location you should put the python file with your module (excluding the numpy/__init__.py) so for me that would be

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site- packages

To do this just go to your terminal and type

mv "location of your module" "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site- packages"

Now you should be able to import your module.

Solution 3:

This is something that works for me (I have to frequently create python packages that are uploaded to a private pip repository). elaborating on the comment by @joran on the question.

  1. create a "build directory" which is used as a workspace to create packages. any directory of your choice will do
  2. Copy your python package dir there, and create a setup.py file. this should help in creating the setup.py correctly.
  3. create a virtualenv for the project you are working on. virtualenvs have a bunch of other benefits, I am not going into the details here.
  4. create a local dist package python setup.py sdist --format=tar. the package created should ideally be in the dist folder.
  5. Install the package on your virtualenv (after activating it). pip install <yourpackage>.tar

you can use pip install --force-reinstall if you need to play around with the libraries more and re-create the dist packages.

I've found that this method works great for me. If you do not need to package the modules for use of other systems instead of just your local, this method might be an overkill

Happy hacking.

Solution 4:

On my Mac, I did a sudo find / -name "site-packages". That gave me a few paths like /Library/Python/2.6/site-packages, /Library/Python/2.7/site-packages, and /opt/X11/lib/python2.6/site-packages.

So, I knew where to put my modules if I was using v2.7 or v2.6.

Hope it helps.