Run python on ubuntu to connect to pg. the following error occurs: ImportError: No module named psycopg2, ttupython

Source: Internet
Author: User

Run python on ubuntu to connect to pg. the following error occurs: ImportError: No module named psycopg2, ttupython
Run python on ubuntu to connect to pg. The error ImportError: No module named psycopg2 is returned.


Root @ pgproxy1 :~ # Python/home/zxw/PGWriterTest_m.py
Traceback (most recent call last ):
File "/home/zxw/PGWriterTest_m.py", line 4, in <module>
Import psycopg2
ImportError: No module named psycopg2


Install the SDK as follows:
1
Root @ pgproxy1 :~ # Apt-cache search psycopg2
Python-psycopg2-Python module for PostgreSQL
Python-psycopg2-dbg-Python module for PostgreSQL (debug extension)
Python-psycopg2-doc-Python module for PostgreSQL (documentation package)
Python3-psycopg2-Python 3 module for PostgreSQL
Python3-psycopg2-dbg-Python 3 module for PostgreSQL (debug extension)


2
Root @ pgproxy1 :~ # Python-V
Python 2.7.3


3
Root @ pgproxy1 :~ # Apt-get install-y python-psycopg2 python-psycopg2-doc python-psycopg2-dbg
Reading package lists... Done
Building dependency tree
Reading state information... Done
...
Processing triggers for libc-bin...
Ldconfig deferred processing now taking place
Root @ pgproxy1 :~ #


4
The script is as follows:
# -- Encoding: UTF-8 --
Import time
Import threading
Import psycopg2
Import Queue
Import datetime




Class PGWriterTest (threading. Thread ):
"Initialization """
Def _ init _ (self, connstr ):
Self. conn = psycopg2.connect (connstr)
Self. cursor = self. conn. cursor ()

Self. dbnum = 4
Self. connArray = []
Self. cursorArray = []


For I in range (0, self. dbnum ):
# DB port
Dbidstr = '% 02d' % (9900 + I)
If (I = 0 or I = 2 ):
DstDB = 'host = ip1 user = dbusername password = pwd dbname = dbname port = '+ dbidstr
Else:
DstDB = 'host = ip2 user = dbusername password = pwd dbname = dbname port = '+ dbidstr
Print 'connect '+ dstDB

DstConn = psycopg2.connect (dstDB)
Self. connArray. append (dstConn)
DstCursor = dstConn. cursor ()
Self. cursorArray. append (dstCursor)

# Run the constructor of the parent class
Threading. Thread. _ init _ (self)


"Writing data to Database """
Def read (self, t_id ):
SQL = 'select * from get_cont ('+ str (t_id) + ')'
Self.cursor.exe cute (SQL)
Datalist = []
For row in self. cursor. fetchall ():
Datalist. append (row)
Return datalist

"Writing data to Database """
Def save (self, t_id, data ):
SQL = 'select write_cont (% s, character (255) % s, % d, NOW (): timestamp ))'
Params = []
Params. append (t_id)
Params. append (data [1])
Params. append (data [2])
Params. append (data [3])


# Print params
# Db_ins_id
Db_ins_id = 0
Db_ins_id = t_id % self. dbnum
Try:
Print str (datetime. datetime. now () + "DB" + str (db_ins_id) + "" + str (t_id) + "before insert"
Insert_ SQL = 'select write_cont (% s, character (255) % s, % d, NOW (): timestamp ))'
Self.cursorarraymongodb_ins_id0000.exe cute (insert_ SQL, params)
Self.cursorarraymongodb_ins_id=.exe cute ("COMMIT ")
Print str (datetime. datetime. now () + "DB" + str (db_ins_id) + "" + str (t_id) + "inserted"
Return True


Failed t Exception, ex:
Print ("save error: % s" % str (ex ))
Print ("save t_id: % s \ t" % str (t_id ))
Print ("error cont: % s" % str (params ))
# Self. log. write ("error param: % s" % str (params ))
# Self. log. write ("error t_id: % s" % data. get ('t_id ',''))
Self.cursorarraymongodb_ins_idcmd.exe cute ("ROLLBACK ")
Return False



# Test reading
"""
Try:
Searchsql = 'select t_id from get_cont ('+ str (t_id) + ')'
Self.cursorarraymongodb_ins_id+.exe cute (searchsql)
Data = self. cursorArray [db_ins_id]. fetchone ()
If (data = None or int (data [0])! = T_id ):
Print 'insert error for '+ str (db_ins_id) + searchsql
Failed t Exception, searchex:
Print str (searchex) + 'for' + searchsql
"""
Return True
If _ name _ = "_ main __":
PgTest = PGWriterTest ('host = ip user = DBUser password = pwd dbname = DBNAme port = 8080 ')
Start_time = str (datetime. datetime. now ())
For I in range (1, 10 ):
T_id = 1000 + I;
Print str (datetime. datetime. now () + "getting"
Rows = pgTest. read (t_id)

Print str (datetime. datetime. now () + "gotten"
# Print rows [0]
PgTest. save (t_id, rows [0])
Print start_time

Print str (datetime. datetime. now ())



-----------------

Please refer to the following source for reprinting:
Blog.csdn.net/beiigang

Python ImportError: No module named psycopg2

This is an interface of postgreSQL. It must be installed separately. If you have already installed it. This error is also displayed. You can reinstall it from the source code. Check whether there are any installation errors.

In addition, do you have two python copies on your computer? You have installed them in another external directory.
 
Why does the import hashlib prompt ImportError: No module named hashlib ?? My version is python24

Versions earlier than 2.5 do not contain hashlib. You need to install it yourself.

Pypi.python.org/pypi/hashlib

This is a stand alone packaging of the hashlib library written with Python 2.5 so that it can be used on older versions of Python (tested on 2.3 and 2.4 ).
Reference: www.pythoncool.com/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.