ubuntu上跑python串連pg,報錯 ImportError: No module named psycopg2,ubuntupython

來源:互聯網
上載者:User

ubuntu上跑python串連pg,報錯 ImportError: No module named psycopg2,ubuntupython
ubuntu上跑python串連pg,報錯  ImportError: No module named psycopg2


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


如下安裝:
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
指令碼如下:
# --encoding:utf-8--
import time
import threading
import psycopg2
import Queue
import datetime




class PGWriterTest(threading.Thread):
    """ 初始化 """
    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)
        
        # 運行父類的建構函式
        threading.Thread.__init__(self)


    """ 資料寫入資料庫 """ 
    def read(self,t_id):
        sql = 'SELECT * from get_cont('+str(t_id)+')' 
        self.cursor.execute(sql)
        datalist = []
        for row in self.cursor.fetchall():
            datalist.append(row)
        return datalist    
    
    """ 資料寫入資料庫 """ 
    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.cursorArray[db_ins_id].execute(insert_sql,params)
            self.cursorArray[db_ins_id].execute("COMMIT")
            print str(datetime.datetime.now()) + " DB " + str(db_ins_id) + " " +  str( t_id ) + " inserted"
            return True


        except 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.cursorArray[db_ins_id].execute("ROLLBACK")
            return False


            
            #測試讀取
            """
            try:
                searchsql = 'select t_id from get_cont('+ str(t_id) + ')'
                self.cursorArray[db_ins_id].execute(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
            except Exception,searchex:
                print str(searchex) + ' for  ' + searchsql
            """     
        return True
if __name__ == "__main__":
    pgTest = PGWriterTest('host=ip user=DBUser password=pwd dbname=DBNAme port=9999')
    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())



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

轉載請著明出處:
blog.csdn.net/beiigang

python ImportError: No module named psycopg2

這個是postgreSQL的一個介面。需要單獨安裝。如果你已經安裝了。還顯示這個錯誤。你可以從原始碼那裡重新安裝一次。看看有沒有安裝錯誤。

另外你的電腦上是不是有兩份python,你安裝到了另一外目錄裡。
 
import hashlib 為何提示ImportError: No module named hashlib??我的版本是python24

2.5之前的版本是不包含hashlib的,你需要自己安裝

pypi.python.org/pypi/hashlib

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

相關文章

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.