How to call snowsql client from python

房东的猫 提交于 2021-01-29 06:05:20

问题


I'm calling snowsql client from shell script. I'm importing properties file by doing source. And invoking snowsql client. How can I do the same in Python? Any help would be highly appreciated.

Shell script to call snowsql client:

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

回答1:


Assuming you're switching to using Python purely for improved control flow and would still like to continue using shell features, a straight-forward translation would require writing a function that acts as the source command to import environment variables, then using them in a subprocess call that executes with a shell to 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()

If you are instead looking to go purely Python without any shell calls, then the more native connector offered by Snowflake can be used instead of snowsql. This would be a far more invasive change but the connection examples will help you get started.



来源:https://stackoverflow.com/questions/59893878/how-to-call-snowsql-client-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!