Python调用Hive SQL的两种常用方式及显存优化
本文介绍在Python中执行Hive SQL的两种主要方法:通过os.system直接运行脚本,以及利用os.popen配合pandas读取结果。重点解析如何设置hive.cli.print.header以显示表头,并探讨结合TensorFlow等框架时可能遇到的显存占用问题及优化思路。
本文详细讲解如何在Python环境中编写和执行Hive脚本,通过具体示例代码展示操作流程,为相关开发和学习提供实用参考。
Python执行Hive SQL的两种常用方式
第一种方法:直接执行.sql脚本文件。
import numpy as np
import pandas as pd
import lightgbm as lgb
from pandas import DataFrame
from sklearn.model_selection import train_test_split
from io import StringIO
import gc
import sys
import os
hive_cmd = "hive -f ./sql/sql.sql"
output = os.popen(hive_cmd)
data_cart_prop = pd.read_csv(StringIO(unicode(output.read(),'utf-8')), sep="\t",header=0)
第二种方法:直接在Python中执行Hive语句。
假设存在如下Hive SQL查询需求:
hive_cmd = 'hive -e "select count(*) from hbase.routermac_sort_10;"'
在Python代码中,通常采用以下方式调用上述Hive SQL命令:
os.system(hive_cmd)
---------------------
hive_cmd1 = "hive -f ./user.sql"
output1 = os.popen(hive_cmd1)
test_user = pd.read_csv(StringIO(unicode(output1.read(),'utf-8')), sep="\t",header=0)
hive_cmd2 = "hive -f ./action.sql"
output2 = os.popen(hive_cmd2)
test_action = pd.read_csv(StringIO(unicode(output2.read(),'utf-8')), sep="\t",header=0)
hive_cmd3 = "hive -f ./click.sql"
output3 = os.popen(hive_cmd3)
test_click = pd.read_csv(StringIO(unicode(output3.read(),'utf-8')), sep="\t",header=0)
若希望在输出结果中显示列名(表头),可在脚本中添加配置语句:set hive.cli.print.header=true;
或者,采用以下替代语句实现相同效果:
hive_cmd = 'hive -e "set hive.cli.print.header=true;SELECT * FROM dev.temp_dev_jypt_decor_user_label_phase_one_view_feature WHERE(dt = "2018-09-17");"'
output = os.popen(hive_cmd)
data_cart_prop = pd.read_csv(StringIO(unicode(output.read(),'utf-8')), sep="\t",header=0)
TensorFlow显存占用问题
第三部分:关于TensorFlow显存占用的讨论。
import tensorflow as tf
tf.enable_eager_execution()
x = tf.get_variable('x', shape=[1], initializer=tf.constant_initializer(3.))
with tf.GradientTape() as tape:
y = tf.square(x)
y_grad = tape.gradient(y, x)
print([y.numpy(), y_grad.numpy()])
以上内容为本文的全部总结,希望能为读者的学习或工作带来帮助,欢迎继续支持本站获取更多技术资讯。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













