Installing Psycopg2 with pip works, but cannot import the module on OS X 10.9

I installed psycopg2 using

pip install psycopg2 

and everything went fine. The installation exit had several warnings along the lines

 In file included from ./psycopg/psycopg.h:33: ./psycopg/config.h:71:13: warning: unused function 'Dprintf' [-Wunused-function] static void Dprintf(const char *fmt, ...) {} ^ 1 warning generated. 

but in the end he says

 Successfully installed psycopg2 

and it appears when I run pip list .

Now when I try to import it in python, I get an error:

 $ python Python 2.7.5 (default, Aug 25 2013, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named psycopg2 

Why can't Python import a module if it was successfully installed?

(Python 2.7.5 was installed with Homebrew. Psycopg2 was installed with pip.)

+6
source share
1 answer

OS X already comes with Python 2.7.5; when you install Python with Homebrew, it puts the new version elsewhere without touching the built-in. Homebrew Python also ships with Pip, while OS X does not. What happens here, you use Homebrew pip to install psycopg2, then run OS X python and try to import it.

Run /usr/local/bin/python (full path to Homebrew Python) and try import psycopg2 from there.

If this works, you need to put /usr/local/bin before /usr/bin in your PATH variable so that your shell finds Python Homebrew before OS X every time. If you use Bash (the default shell in OS X), you can do this by placing the following in .bash_profile :

 export PATH=/usr/local/bin:$PATH 

To ensure that you are using the correct Python script in your scripts, use the following shebang line:

 #!/usr/bin/env python 

env will do a PATH search for Python and run the script with the first one it finds, just like typing python from your shell. Bash scripts and such should inherit the PATH variable and find the correct python unchanged.

You can also hardcode the path to Homebrew Python in your shebang line ( #!/usr/local/bin/python ), but this means that your script will only work on OS X machines with Python installed on the home computer and it is better to avoid it.

+5
source

All Articles