从索引中修剪字符串

2024-04-24 12:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个或多或少有效的例子,如您在下面看到的,在openshift中杀死一些pod。你知道吗

现在卡在这一点上了。你知道吗

myindx = out.find(key)
print out[myindx:-1].rstrip()

outoc get pod --all-namespaces ...的输出,如下所示

 -n namespace01 pod-name-9-xd45
 -n namespace01 pod-name-9-xd67
 -n namespace02 pod-name2-9-xd45
 -n namespace02 pod-name2-9-rd45

有了out.find(key),我现在找到了正确的线路,我需要整条线路来调用oc delete $line。你知道吗

在perl中,我会将oc get pod --all-namespaces ...的所有输出放在一个数组中,并搜索数组中的每一行,但在python中如何做到这一点呢?你知道吗

谢谢你的帮助。你知道吗

#!python

import StringIO
import sys
import re
import subprocess
import shlex
from collections import defaultdict

# Since you're keeping counts, we'll initialize this so that the values
# of the dictionary are `int`
myhash = defaultdict(lambda: 0)

if sys.argv[3] != "NodeReady":
     sys.exit(0)

commandline = shlex.split("/bin/oc get pod --all-namespaces")

proc = subprocess.Popen(commandline,stdout=subprocess.PIPE)
out, err = proc.communicate()
buf = StringIO.StringIO(out)


for line in buf.readlines():
#    print line
    """
    Diese Projekte und pod Zeilen werden ignoriert
    """
    if re.match('^NAMESPACE|.*-router|^logging|^default|.*infra-ipfailover|.*-(build|deploy)',line):
        continue
    linesplited = line.split()
    prefix = re.split('(.*)-\d+-\w+$',linesplited[1])
    #print  linesplited[1]
    #print prefix[1]
    myhash[prefix[1]] += 1

commandline = shlex.split('/bin/oc get pod --all-namespaces -o template --template=\'{{range .items }} -n {{ .metadata.namespace }} {{.metadata.name}}\n{{end}}\'')

proc = subprocess.Popen(commandline,stdout=subprocess.PIPE)
out, err = proc.communicate()
#print out
buf = StringIO.StringIO(out)
#print buf

#for line in buf.readlines():
#    print line

for key in myhash.keys():
    print "<<<>>>"
#    print myhash[key] % 2 , "\n"
    print key,":",myhash[key]
    if  myhash[key] % 2 :
        if myhash[key] > 1:
            print "mod 2",key,":",myhash[key]
            myindx = out.find(key)
            print out[myindx].rstrip()
    else:
        print "not mod 2",key,":",myhash[key]
        print out.find(key)

Tags: keyimportgetlineallfindoutpod
1条回答
网友
1楼 · 发布于 2024-04-24 12:13:50

我只是在暗处拍摄,但我认为你的问题可以归结为以下几点。你知道吗

在这行之后,out应该有您提到的所有输出。你知道吗

out, err = proc.communicate() 

out可能是这样的:

-n namespace01 pod-name-9-xd45\n
-n namespace01 pod-name-9-xd67\n
-n namespace02 pod-name2-9-xd45\n
-n namespace02 pod-name2-9-rd45\n

与其将其推入StringIO对象中,不如将此字符串切分为一个数组:

output_lines = [x.strip() for x in output.split('\n')]

然后output_lines看起来像这样:

['-n namespace01 pod-name-9-xd45',
 '-n namespace01 pod-name-9-xd67',
 '-n namespace02 pod-name2-9-xd45',
 '-n namespace02 pod-name2-9-rd45']

然后您需要在数组中找到包含您的键的字符串中的每一个。你知道吗

if  myhash[key] % 2 :
    if myhash[key] > 1:
        print "mod 2",key,":",myhash[key]
        for ol in output_lines:
            myindx = ol.find(key)
            if myindx > -1:
                print ol

相关问题 更多 >