Python中调用gcloud命令时如何捕获HTTPError 404错误
解决方案
错误原因
- 你通过
subprocess调用外部gcloud命令行工具,没有直接使用googleapiclient的Python SDK发起接口请求,所以errors.HttpError异常永远不会被触发,该异常仅适用于直接调用SDK接口的场景 subprocess.run默认不会因命令执行失败(返回值非0)抛出Python异常,需要额外配置参数才能触发异常捕获
方案1:继续使用subprocess调用gcloud命令
这种方式不需要调整你的调用逻辑,只需要修改异常捕获规则和subprocess参数即可:
import subprocess try: print("Applying labels") gcloud_cmd = ['gcloud', 'compute', 'instances', 'add-labels', 'all', '--labels=key=value', '--zone=us-east1-b'] # check=True让命令执行失败时抛异常,capture_output=True捕获错误输出,text=True将输出转为字符串 process = subprocess.run(gcloud_cmd, check=True, capture_output=True, text=True, shell=False) except subprocess.CalledProcessError as e: # stderr中存储了gcloud返回的完整错误内容 error_msg = e.stderr print(f"Command did not succeed because of the following error: {error_msg}") # 可直接匹配错误内容中的关键词做分支逻辑处理 if "HTTPError 404" in error_msg and "was not found" in error_msg: print("匹配到资源不存在的报错,执行后续逻辑")
提示:建议尽量不要使用shell=True,把命令拆成列表形式传入更安全,也能避免很多参数解析的问题
方案2:直接使用googleapiclient SDK调用(推荐)
如果可以不用调用外部gcloud命令,直接用SDK调用逻辑更优雅,此时可以直接捕获errors.HttpError异常:
from googleapiclient import discovery, errors from google.oauth2 import service_account # 初始化SDK客户端,根据你的实际情况配置认证方式 credentials = service_account.Credentials.from_service_account_file('你的服务账号密钥文件路径.json') service = discovery.build('compute', 'v1', credentials=credentials) project = 'matei-testing-4010-5cbdeeff' zone = 'us-east1-b' instance = 'all' try: print("Applying labels") # 修改实例标签前需要先获取当前实例的label fingerprint,作为修改请求的必填参数 instance_data = service.instances().get(project=project, zone=zone, instance=instance).execute() current_fingerprint = instance_data['labelFingerprint'] # 执行添加标签操作 body = { "labels": {"key": "value"}, "labelFingerprint": current_fingerprint } request = service.instances().setLabels(project=project, zone=zone, instance=instance, body=body) response = request.execute() except errors.HttpError as e: print(f"Command did not succeed because of the following error: {e}") if e.resp.status == 404: print("匹配到资源不存在的报错,执行后续逻辑")
内容的提问来源于stack exchange,提问作者happymatei
相关产品推荐
相关产品推荐

