如何获取所有可能响应模式的容器名称?

How to get the container names for all possible response pattern?

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

我可以通过 (.*)\s{2,}(Up.*\s+)\s{2,}(\d+\..*)\s{2,}(.*)

找到 RESPONSE1STATUS & NAMES
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

我可以通过 (.*)\s{2,}(Exit.*\s+)\s{2,}\s{2,}(.*)

找到 RESPONSE2 的状态和名称
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)

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

也许你可以尝试以下方法:

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()]))

对回复的一点解释:

  1. 它会找到第一个 ago,只有一个 space 并且附近至少有 2 个 space。
  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