Wednesday, April 22, 2015

Postgresql: Python: Installing pyscopg on Red Hat 6.4

Usually, the psycopg2 installed without issue. Today, having some library issue may be due to the order of postgresql and python being install where during the psycopg2 installation did not find the default postgresql install.


Step 1: If you already have postgresql installed then just install psycopg2


yum install python-psycopg2

Step 2: Create a basic python script to test the connection. Remember to chown and chmod u+x of the script


#!/usr/bin/python2.4
#
# Small script to show PostgreSQL and Pyscopg together
#
import psycopg2
try:
    con = psycopg2.connect("dbname='vcdb' user='vc'")
    cur = con.cursor()
    cur.execute('SELECT version()')
    ver = cur.fetchone()
    print ver
except:
    print "I am unable to connect to the database"
~
~


[postgres@localhost ~]$ python testconn.py
Traceback (most recent call last):
  File "testconn.py", line 5, in <module>
    import psycopg2
  File "/usr/lib64/python2.6/site-packages/psycopg2/__init__.py", line 69, in <module>
    from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: libpq.so.5: cannot open shared object file: No such file or directory

This is due to psycopg2 unable to find the postgres libraries.


Step 3: Locate where the postgres is


[postgres@localhost ~]$ ps -ef|grep postgres
.... .. ..  (know where the pg libraries are ) ...


[postgres@localhost ~]$ find /opt/postgres/ -name libpq.so.5
/opt/postgres/9.3/lib/libpq.so.5


Step 4: include the libraries path


LD_LIBRARY_PATH=/opt/postgres/9.3/lib/
export LD_LIBRARY_PATH


Step 5: Run the test script again


[postgres@localhost ~]$ python testconn.py
(600, 'VirtualCenter Database 6.0')