如何从python调用snowsql客户机

2024-04-26 11:09:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从shell脚本调用snowsql客户端。我正在通过源代码导入属性文件。以及调用SQL客户机。如何在Python中实现同样的功能?任何帮助都将不胜感激

调用snowsql客户端的Shell脚本:

source /opt/data/airflow/config/cyrus_de/snowflake_config.txt


sudo /home/user/snowsql -c $connection --config=/home/user/.snowsql/config -w $warehouse  --variable database_name=$dbname --variable stage=$stagename  --variable env=$env  -o exit_on_error=true -o variable_substitution=True -q /data/snowsql/queries.sql

Tags: 文件env脚本config客户端homesqldata
1条回答
网友
1楼 · 发布于 2024-04-26 11:09:49

假设您切换到使用Python纯粹是为了改进控制流,并且仍然希望继续使用shell功能,那么直接的转换将需要编写一个函数acts as the source command来导入环境变量,然后在子流程调用中使用它们,该子流程调用使用shell执行allow environment variable substitution

import os, shlex, subprocess

def source_file_into_env():
  command = shlex.split("env -i bash -c 'source /opt/data/airflow/config/cyrus_de/snowflake_config.txt && env'")
  proc = subprocess.Popen(command, stdout = subprocess.PIPE)
  for line in proc.stdout:
    (key, _, value) = line.partition("=")
    os.environ[key] = value
  proc.communicate()

def run():
  source_file_into_env()

  subprocess.run("""sudo /home/user/snowsql \
      -c $connection \
       config=/home/user/.snowsql/config \
      -w $warehouse \
       variable database_name=$dbname \
       variable stage=$stagename \
       variable env=$env \
      -o exit_on_error=true \
      -o variable_substitution=True \
      -q /data/snowsql/queries.sql""", \
    shell=True, \
    env=os.environ)

if __name__ == '__main__':
  run()

如果您希望使用纯Python而不使用任何shell调用,那么可以使用更多的native connector offered by Snowflake来代替snowsql。这将是一个更具侵入性的变化,但connection examples将帮助您开始

相关问题 更多 >