如何从 python 中的标准输出 (stdout) 获取字段值?

How to fetch field value from standard output (stdout) in python?

我正在尝试从 python 中的标准输出中获取一个值。这是我从命令行 运行 列出 GKE 集群中的防火墙的命令。

gcloud compute firewall-rules list \
  --project <myproject> \
  --filter="name~gke-cluster-123456789*"

当命令在堡垒服务器上执行时,输出如下:

NAME                      NETWORK  DIRECTION  PRIORITY  ALLOW                         DENY  DISABLED
gke-cluster-XXX-all  default  INGRESS    1000      tcp,udp,XXX                         False
gke-cluster-XXX-ssh  default  INGRESS    1000      tcp:XX                              False
gke-cluster-XXX-vms  default  INGRESS    1000      icmp,tcp:1-XXXXX,udp:1-XXXXX        False

我需要在 python 中执行相同的操作,但只获取名称字段。但是,下面的代码获取防火墙名称以及 NAME 标签。

我的部分代码

cmd = gcloud compute firewall-rules list --project <myproject> --filter="name~gke-cluster-123456789*"
stdin,stdout,stderr = ssh.exec_command(cmd)
for line in stdout.read().splitlines():
   print(line.split()[0])

实际输出:

NAME
gke-cluster-XXX-all
gke-cluster-XXX-ssh
gke-cluster-XXX-vms

预期输出:(我需要的是)

gke-cluster-XXX-all
gke-cluster-XXX-ssh
gke-cluster-XXX-vms

如何删除输出的第一行?

for index, line in enumerate(text.splitlines()):
    if index != 0:
        print(line.split()[0])

您可以单独使用 gcloud 执行此操作:

gcloud compute firewall-rules list \
--filter=${FILTER} \
--format="value[no-heading](name)" \
--project=${PROJECT}

参见:https://cloud.google.com/sdk/gcloud/reference/topic/formats

为了完整起见,您还可以在bash命令行处理跳行:

python <script> | tail -n +2