python连接hive

1 准备连接hive的python代码
 
在使用Python连接hive之前需要将hive中的文件拷贝到python的sys.path中
cp -r $HIVE_PATH/lib/py     /usr/local/lib/python2.7/site-packages
或者将hive中连接代码,设法加入到python的eclipse项目中
总之,目的只有一个,就是用hive自己提供的python客户端代码,来连接hive
关于具体如果将第三方的python代码加入环境变量,可以参照python中添加环境变量
 
 
2 启动hive 的thrift
 
如果hive机器没有thrift请先安装,
确保以下服务开启:
hive --service hiveserver  
 
 
3 写代码连接hive
 
hive的ip是机器的ip,端口默认为10000
-------------------------------------------------------------------
import sys  
from hive_service import ThriftHive  
from hive_service.ttypes import HiveServerException  
from thrift import Thrift  
from thrift.transport import TSocket  
from thrift.transport import TTransport  
from thrift.protocol import TBinaryProtocol  
  
def hiveExe(sql):  
  
    try:  
        transport = TSocket.TSocket('127.0.0.1', 10000)   
        transport = TTransport.TBufferedTransport(transport)  
        protocol = TBinaryProtocol.TBinaryProtocol(transport)  
        client = ThriftHive.Client(protocol)  
        transport.open()  
 
        client.execute(sql)  
 
        print "The return value is : "   
        print client.fetchAll()  
        print "............"  
        transport.close()  
    except Thrift.TException, tx:  
        print '%s' % (tx.message)  
  
if __name__ == '__main__':  
    hiveExe("show tables")  
--------------------------------
posted @ 2014-04-01 21:14  subsir  阅读(2612)  评论(0编辑  收藏  举报