【问题标题】:Catch "HTTPError 404" in python for gcloud commands在 python 中为 gcloud 命令捕获“HTTPError 404”
【发布时间】:2021-08-28 13:20:29
【问题描述】:

试图捕捉这个错误:

ERROR: (gcloud.compute.instances.add-labels) HTTPError 404: The resource 'projects/matei-testing-4010-5cbdeeff/zones/us-east1-b/instances/all' was not found

尝试了不同版本的代码,但没有一个对我有用。

我当前的代码似乎没有发现错误:

from googleapiclient import discovery, errors

try:
    print("Applying labels")
    gcloud_value = (f'gcloud compute instances add-labels all --labels="key=value" --zone=us-east1-b')
    process = subprocess.run([gcloud_value], shell=True)
except errors.HttpError:
   print("Command did not succeed because of the following error: {}".format(errors.HttpError))

如何捕捉错误以便以后使用?

谢谢

【问题讨论】:

  • 子进程的返回值将只是可执行文件的退出代码除非您得到标准输出/错误并对其进行分析。您当然无法以您希望的方式捕获 HttpError 异常
  • 我想要达到的目的是在出现此资源不存在的错误后记下。我和你说的有同样的感觉,但是我将如何通过获取 stdout/stderr 来实现我想要的,你有 python 的小例子吗?有没有办法像 grepping 错误文本将其标记为错误?或者有什么想法?感谢您的回答!

标签: python api gcloud


【解决方案1】:

试试这个:-

import subprocess
gcloud_value = 'gcloud compute instances add-labels all --labels="key=value" --zone=us-east1-b'
process = subprocess.run(gcloud_value, shell=True, capture_output=True)
print(process.stdout.decode('utf-8'))
print(process.stderr.decode('utf-8'))
print(process.returncode)

人们会期望 gcloud 向 stderr 发出错误。因此,通过检查 process.stderr,您应该能够找出问题所在(如果有的话)。此外,如果 process.returncode 不为零,您应该能够推断它不起作用,但这完全取决于底层应用程序(在本例中为 gcloud)的编写方式。即使发生故障,也有很多东西返回零!

【讨论】:

    【解决方案2】:

    我强烈建议您考虑使用 Google 的客户端库与其服务进行交互,而不是 subprocess'ing。

    当您遇到调用 shell 时,不仅会限制错误处理,而且通常需要字符串“munging”,这也是不精确的临时身份验证。

    Google 通常会为其所有服务提供机器生成的“完美”SDK 实现。对于 Cloud(Compute 除外!?),还有 Cloud Client 库。

    我鼓励您探索使用 Python SDK for Compute Engine:

    https://cloud.google.com/compute/docs/tutorials/python-guide

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 2021-09-03
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多