首页 > 解决方案 > 如何获取所有可能响应模式的容器名称?

问题描述

sudo docker ps -a , to check the status of containers.

回应1:

CONTAINER ID        IMAGE                 COMMAND             CREATED             
STATUS              PORTS                                                             
NAMES
3f8ac711da37        local_discourse/app   "/sbin/boot"        23 hours ago        
Up 23 hours         0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:300-
>3000/tcp   name1
3f8ac700ba37        local_discourse/app   "/sbin/boot"        20 hours ago        
Up 23 hours         0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:300-
>3000/tcp   name2

我可以找到STATUS& NAMESfor RESPONSE1,通过使用(.*)\s{2,}(Up.*\s+)\s{2,}(\d+\..*)\s{2,}(.*)

m = re.finditer('(.*)\s{2,}(Up.*\s+)\s{2,}(\d+\..*)\s{2,}(.*)', resp, re.MULTILINE)
for i, j in enumerate(m):
    dict[m.group(4)] = m.group(2)

回应 2:

3f8ac711da37        local_discourse/app   "/sbin/boot"        23 hours ago     Exited (1) 50 minutes ago    name1
3f8ac700ba37        local_discourse/app   "/sbin/boot"        20 hours ago     Exited (135) 50 minutes ago  name2

我可以通过以下方式找到 RESPONSE2 的状态和名称(.*)\s{2,}(Exit.*\s+)\s{2,}\s{2,}(.*)

m = re.finditer('(.*)\s{2,}(Exit.*\s+)\s{2,}\s{2,}(.*)', resp, re.MULTILINE)
for i, j in enumerate(m):
    dict[m.group(3)] = m.group(2)

我正在尝试制作一个通用的正则表达式,它可以为任何类型的响应获取STATUS& NAME(状态可以是UP, Exit & Stopped)。可能吗 ?

标签: pythonregexmultiline

解决方案


也许您可以尝试以下操作:

import subprocess
import re

resp = subprocess.check_output('docker ps -a', shell = True)

item = re.finditer('.*?\s{1}ago\s{2,}(.*?\s).*\s{2,}(.*)', resp, re.MULTILINE)
for i in item:
    print(' : '.join([i.group(1).strip(), i.group(2).strip()]))

对 re 的一点解释:

  1. 它会找到第一个ago只有一个空间和附近至少 2 个空间的空间。
  2. (.*?\s)将找到容器状态
  3. 最后,(.*)将找到容器名称。

输出如下:

Exited : mystifying_hoover
Exited : abc_1
Exited : infallible_agnesi
Exited : laughing_curran
Exited : eager_clarke
Exited : youthful_northcutt
Exited : nostalgic_mclean
Exited : jolly_turing
Created : determined_curran
Exited : peaceful_mestorf
Exited : awesome_jones
Up : cc_2
Up : celery_worker
Up : dpps
Up : celery_broker2
Up : rdebug
Up : rdebug2
Up : cassandra

推荐阅读