0

我正在从 shell 脚本调用 snowsql 客户端。我正在通过源代码导入属性文件。并调用 snowsql 客户端。我怎样才能在 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
4

1 回答 1

1

假设您转而使用 Python 纯粹是为了改进控制流,并且仍想继续使用 shell 功能,那么直接转换需要编写一个函数作为源命令来导入环境变量,然后在子进程中使用它们使用 shell 执行以允许环境变量替换的调用:

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()

如果您希望在没有任何 shell 调用的情况下使用纯 Python,那么可以使用Snowflake 提供的更原生的连接器snowsql来代替. 这将是一个更具侵入性的更改,但连接示例将帮助您入门。

于 2020-01-26T11:34:50.717 回答