[英]Get a value from columns in the output of Python subprocess.call
在解釋我的問題之前,我想提及一下,我在StackOverflow上看過其他各種問題,但是找不到與我的問題相關的任何解決方案。 所以,這就是為什么請不要將此標記為重復!
我正在研究一個Python(3.6)項目,在該項目中,我需要運行終端命令並從輸出中解析出以列形式的值。
這是我運行的命令:
output = subprocess.call('kubectl get svc', shell=True)
這是輸出:
b'NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.35.240.1 <none> 443/TCP 28m
node-app1 LoadBalancer 10.35.245.164 35.239.29.239 8000:32249/TCP 26m
現在,我需要從第二行和第四列獲取EXTERNAL-IP
。
我如何獲得該價值?
您可以從外殼程序本身提取特定的列。 這樣,我們可以避免文本處理所產生的開銷。
out = subprocess.check_output(["kubectl get svc | awk '{print $3}'"], shell=True)
result = out.decode().split('\n')
print(result[1])
輸出:
10.0.0.1
外殼很不錯。 怎么樣
output = subprocess.call('kubectl get svc | tr "\t" " " | tr -s " " | cut -d " " -f 4 | tail -1', shell=True)
您也可以省略tail -1
,它給出最后一行,並在Python中進行拆分/過濾。
您也可以自己在python中解析輸出:
# Step 1, convert the bytes output into string
output = output.decode('utf-8')
# Step 2, split the string based on the newline character
output = output.split('\n')
# Step 3, split all lines on any whitespace character
output = [o.split() for o in output]
# Step 4, get the correct value as [row][column]
value = output[2][3]
您可以使用熊貓讀取數據。 這是一個獨立的示例:
from StringIO import StringIO
import pandas
x=b"""NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.35.240.1 <none> 443/TCP 28m
node-app1 LoadBalancer 10.35.245.164 35.239.29.239 8000:32249/TCP 26m"""
dataframe = pandas.read_csv(StringIO(x), sep="\s+")
# print rows
for index, row in dataframe.iterrows():
print (row['NAME'], row['CLUSTER-IP'], row['PORT(S)'])
# search for a row with name node-app1 and print value in PORT(S) column:
print dataframe.loc[dataframe['NAME'] == 'node-app1']['PORT(S)'].to_string(index=False)
使用一些字符串操作
演示:
output = b"""NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.35.240.1 <none> 443/TCP 28m
node-app1 LoadBalancer 10.35.245.164 35.239.29.239 8000:32249/TCP 26m"""
output = iter(output.split("\n"))
next(output) #Skip Header
for i in output:
print(i.split()[3]) #str.split and get index 3
輸出:
<none>
35.239.29.239
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.