Python 从 运行 shell 命令获取输出 - gcloud create dataproc cluster

Python getting output from running shell command - gcloud create dataproc cluster

我尝试使用 python[从 运行 gcloud-dataproc-create-cluster 获取 expire-dataproc-tag

我试过 subprocess.Popen,我认为这个问题是错误的,或者检索结果需要很长时间,我最终得到了空的字符串

我试过命令,command_1 工作正常,问题出现在 运行 command_2

import subprocess

command = "echo hello world"
command_1 = "gcloud compute images list --project {project-id} --no-standard-images"
command_2 = 'gcloud beta dataproc clusters create cluster-name --bucket {bucket} --region europe-west1 --zone europe-west1-b --subnet {subnet} --tags {tag} --project {project-id} --service-account {service-account} --master-machine-type n1-standard-16 --master-boot-disk-size 100 --worker-machine-type n1-standard-1 --worker-boot-disk-size 100 --image {image} --max-idle 2h --metadata enable-oslogin=true --properties {properties} --optional-components=ANACONDA,JUPYTER,ZEPPELIN --enable-component-gateway --single-node --no-address'.split(' ')

process = subprocess.Popen(command_2, stdout=subprocess.PIPE, shell=True)
# process.wait()
try:
    print('inside-try')
    result, err = process.communicate()
    result = result.decode('utf-8')
except Exception as e:
    print('The Error', e)

print('the result: ', result)
print("the-error: ", err)

输出是

inside-try  
ERROR: (gcloud.beta.dataproc.clusters.create) INVALID_ARGUMENT: Dataproc custom image '{image-name}' has expired. Please rebuild this custom image. To extend the custom image expiration date to '2022-02-11T08:29:58.322549Z', please use this cluster property during cluster creation: 'dataproc:dataproc.custom.image.expiration.token=1.{image-name-properties......}'               
the result: 
the-error: None

我正在尝试获取错误:.... 输出到结果变量(在结果之后打印)

您没有从进程中捕获 stderr

尝试:

process = subprocess.Popen(
    command,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
)

所以 err 没有被 result, err = process.communicate()

设置

进行上述更改后,err 将包含您收到的错误消息。

我强烈建议您考虑使用 Google 的 SDK 与其服务进行交互。这些不仅更易于使用,而且您可以发送 Python 个对象,而不是发送子流程的字符串 in/out。

这是 Python 中 Creating a Dataproc cluster 的文档。