从Python subprocess.call的输出中的列获取值

问题描述 投票:0回答:5

在解释我的问题之前,我想提一下,我已经在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

我怎样才能获得这个价值?

python python-3.x subprocess
5个回答
3
投票

您可以从shell本身提取特定列。这样我们就可以避免文本处理产生的开销。

out = subprocess.check_output(["kubectl get svc | awk '{print $3}'"], shell=True)
result = out.decode().split('\n')
print(result[1])

输出:

10.0.0.1

2
投票

外壳很不错。怎么样

output = subprocess.call('kubectl get svc | tr "\t" " " | tr -s " " | cut -d " " -f 4 | tail -1', shell=True)

你也可以省略tail -1,它给出了最后一行,并在Python中进行了拆分/过滤。


2
投票

您也可以在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]

1
投票

使用一些字符串操作

演示:

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

1
投票

您可以使用pandas来读取数据。这是一个自包含的例子:

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)
© www.soinside.com 2019 - 2024. All rights reserved.