Python執行hive sql

該python腳本是用於執行hive腳本的,需要設置hive的可執行環境變數,其實質轉化為shell下命令 hive -e 'sql語句』 的方式執行,然後把結果重定向到控制台顯示。註:由於該腳本是直接調用shell中的hive命令,所以需要在安裝hive的伺服器上執行。

使用前置條件:(1)安裝hadoop和hive,並啟動完hadoop;(2)已配置好hive的環境變數,確保在shell中能正常執行hive。

#!/usr/bin/python  #-*-coding:utf-8 -*-    import subprocess  import traceback    sql = """  # 書寫hql腳本  ;  """  cmd = 'hive -e """'+sql.replace('"', "'")+'"""'  print cmd  try:      p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)      while True:          buff = p.stdout.readline()          print buff          if buff == '' and p.poll() != None:              break    except Exception,re:      print "message is:%s" %(str(re))      traceback.print_exc();

腳本舉例

#!/usr/bin/python  #-*-coding:utf-8 -*-  import subprocess  import traceback  sql = """    select * from app_tianhe_zym_item_reason_dtl_da where order_dt = '2016-01-26' limit 10;  """  cmd = 'hive -e """'+sql.replace('"', "'")+'"""'  print cmd  try:      p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)      while True:          buff = p.stdout.readline()          print buff          if buff == '' and p.poll() != None:              break  except Exception,re:      print "message is:%s" %(str(re))      traceback.print_exc();