2017-09-07 4 views
0

私は現在、以下に示すように、オープンシフトのいくつかのポッドを殺すために多かれ少なかれ実際の例を持っています。インデックスからトリム文字列を取り除く

これでこの時点で固まっています。

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

outout.find(key)この

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

私は今右の行を見つけ、私はoc delete $lineを呼び出すための行全体を取得する必要がありますように見えますoc get pod --all-namespaces ...の出力です。

私は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) 

答えて

1

私は暗闇の中で少し撮影していますが、あなたの問題は次のように軽減できると思います。

この行の後には、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 
+0

ありがとうございました。私は少しそれを採用しているが、コンセプトは動作する;-) – Aleksandar

関連する問題