Search code examples
pythonimportmodulepipsudo

Python module Installing


I wrote this command to install NLTK python module :

sudo pip install -U nltk

The first time it seemed to work well but when I wanted to test it, it didn't. So I re-wrote the command and then I got

The directory '/Users/apple/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

I tried every chown command possible, I don't know what I can do more. I use a Mac OS X 10.9.5.


Solution

  • You'll want to create a virtualenv to install Python packages. This prevents the need to install them globally on the machine (and generally makes installing modules less painful). We'll also include virtualenvwrapper to make things easier.

    The steps are to install virtualenv and virtualenvwrapper with pip:

    pip install virtualenv virtualenvwrapper
    

    This may require sudo - if so, just sudo pip install virtualenv virtualenvwrapper.

    Add the following lines to your ~/.bashrc:

    # Add WORKON_HOME to be the location of all virtual environments
    export WORKON_HOME=~/Envs
    # Gives us `workon` and `deactivate`
    source /usr/local/bin/virtualenvwrapper.sh
    

    Source your ~/.bashrc

    . ~/.bashrc
    

    Next, create the virtual environment. I'll generically call this one venv:

    mkvirtualenv venv
    

    Now you'll want to do work in that virtual environment. To do this, you'll want to issue workon:

    workon venv
    

    Now you can install your packages like normal.

    pip install nltk
    ...
    

    When you're done doing work, just deactivate your virtualenv.

    deactivate
    

    Next time you want to do work, just issue workon venv again and all of your modules will still be associated with that virtual environment.