Python调用Hive SQL的两种常用方式及显存优化

咖啡半糖
咖啡半糖
发布时间:2026-10-13| 4人浏览过
原创

本文介绍在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()])

以上内容为本文的全部总结,希望能为读者的学习或工作带来帮助,欢迎继续支持本站获取更多技术资讯。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。