繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM