从python执行配置单元脚本时的参数替换

egmofgnx  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(372)

我必须从python对配置单元执行以下查询:

SELECT * FROM user WHERE age > ${hiveconf:AGE}

目前,我有以下工作代码段:

import pyhs2
with pyhs2.connect(host='localhost',
                   port=60850,
                   authMechanism="PLAIN",
                   user='hduser',
                   database='default') as conn:
    with conn.cursor() as cur:
        cur.execute("SELECT * FRPM user WHERE age > ?", 10)

所以我可以用pyhs2将参数传递给查询。但是如何从python代码中执行变量替换以不更改原始查询(即replace) ${hiveconf:AGE} 以干净的方式提供一些价值)?

zzoitvuj

zzoitvuj1#

可以在python中使用子进程。您可以将sql存储在seprate文件中,并使用以下格式执行它。您还可以添加更多变量

import subprocess
 value1=your_value
 p=subprocess.Popen("hive -f /sql/file/location/script.hql"+" --hiveconf variable1="+value1,shell=True,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE)
 out, err = p.communicate()

 if err==None:
    print "successfull"
else:
    print "not successfull"

或者,如果您想执行它,下面的pyhs2方法是execute语句的格式。

cur.execute("SELECT * FROM user WHERE age > %d"% 10)
xuo3flqw

xuo3flqw2#

像这样的事

def get_sql(substitution="${hiveconf:AGE}"):
    sql = "select * from bla where blub > {variable}"
    sql = sql.format(variable=substitution)
    return sql

结果:

get_sql()
"select * from bla where blub > ${hiveconf:AGE}"

get_sql("test")
"select * from bla where blub > test"

有关格式语法的详细信息,请参见:https://docs.python.org/2/library/string.html#format-字符串语法

相关问题