【问题标题】:How can I run cloud shell commands from Python?如何从 Python 运行云 shell 命令?
【发布时间】:2022-01-24 13:19:27
【问题描述】:

我一直在尝试自动化我的 GCP 数据流系统。由于一些并行化问题,与压缩的 gzip 文件相比,未压缩的 txt 文件加载到管道中的速度要快得多。所以,我必须先在 google 交互式 shell 中使用 gsutil 命令将我的 gzip 文件转换为 txt 文件:

gsutil cat gs://nse-fao-data-test/FAO* | zcat |  gsutil cp - gs://nse-fao-data-test/uncomp/hello9.txt

现在为了使系统自动化,我尝试在我的本地运行这个 gcloud shell,方法是在 python 中给出 OS 命令,并在我的管道开始之前每次调用它:

import os
import subprocess

def uncompress(in_file = 'gs://nse-fao-data-test/FAO*',out_file="gs://nse-fao-data-test/uncomp/uncompressed.txt"):
    subprocess.call("gsutil cat {0} | zcat |  gsutil cp - {1}".format(in_file,out_file))
    
def openShell():
    os.system("gcloud cloud-shell ssh --authorize-session")

虽然 openShell 命令有效并在我的本地启动 gcloud shell,但未执行解压缩。有什么方法可以自动执行 uncompress() 函数中的命令,而无需手动编写?

【问题讨论】:

    标签: python google-cloud-platform google-cloud-storage apache-beam google-cloud-shell


    【解决方案1】:

    os.system 在自己的环境中运行,当您调用的命令结束时,它将退出。所以你的授权会话在通话后就消失了。

    您可以改用subprocess.Popen 结帐并运行多个命令。

    有一个good answer on how to use it

    并链接到子进程解释状态:“此模块打算替换 几个较旧的模块和功能”用explanation on 如何替换 os.system 命令

    编辑:对于 gcloud cloud-shell ssh 上的特定用例,它会打开一个新的“交互式”会话,您不能以编程方式传递命令,而是可以使用 --command=XXX 参数同时运行它

    To run a remote command in your Cloud Shell, run:
    $ gcloud cloud-shell ssh --command=ls
    

    对于 windows putty,您需要允许批处理 putty,因为它要求输入 Return 键。

    【讨论】: