此处,以获取在OS上执行数据库Hive或Mysql命令"show tables“结果为例;实际上,获取数据库的select结果及常规的Linux命令结果的道理都是一样的。
/Users/nisj/PycharmProjects/BiDataProc/love/selectQuery_inHiveMysql.py
# -*- coding=utf-8 -*- import os import re def selectQuery(): selectResult_data = os.popen("""/usr/bin/mysql -hMysqlHost -P50514 -uMysqlUser -pMysqlPass --default-character-set=utf8 -N -e "set names utf8; \ use jellyfish_user; \ show tables; \ " """).readlines(); sqd_list = [] for sq_list in selectResult_data: sq = re.split('\t', sq_list.replace('\n', '')) sqd_list.append(sq) i = 0 for sqd in sqd_list: i = i + 1 print sqd[0], i def selectQueryHive(): selectResult_data = os.popen("""/usr/lib/hive-current/bin/hive -e " use default; \ show tables; \ " """).readlines(); for tabName in selectResult_data: if "xxx" in tabName: print tabName.strip() # batch test selectQuery() selectQueryHive()