我正在研究一个Python(3.6)项目,在该项目中,我需要从subprocess.check_output的表格输出中解析数据。
这是我的使用方式: 输出为:
NAME HOSTS ADDRESS PORTS AGE
mysvcs * 107.178.250.150 80 1m
这样会为ADDRESS加载一个空列,如下所示:
NAME HOSTS ADDRESS PORTS AGE
mysvcs * 80 1m
但是过了一会儿,它会将107.178.250.150
加载到第二行的第三列中。
因此,如何填充此address
。
这是我的尝试方式:
address = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True)
all_address = out_ip.decode().split('\n')
print(all_address)
address = all_address[1]
print(address)
if not address:
while address == '':
out_address = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True)
all_address = out_ip.decode().split('\n')
ip = all_address[1]
print(address)
但是它甚至没有运行while循环并输出为:
b'ADDRESS\n80\n' ['ADDRESS', '80', ''] 80
更新:这是我尝试stovfl答案的方式:
ip = ''
# Limit to 5 loops
for n in range(5):
result = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True)
# Make a List from the result, spliting at NewLine
_list = result.decode().split('\n')
# Check if Value 2 (Index==1) matches a IP Address
if re.match(r'(\d+\.\d+\.\d+\.\d+)', _list[1]):
ip = _list[1]
print("match:{}".format(_list[1]))
# End the loop
break
# Wait a second, before next try
time.sleep(1)
address = 'http://' + ip
答案 0 :(得分:1)
问题:解析表格输出,循环直到获得IP地址
import time, re
# Limit to 5 loops
for n in range(5):
result = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True)
# Make a List from the result, spliting at NewLine
_list = result.decode().split('\n')
# DEBUG
print("list:{}".format(_list))
# Check if Value 2 (Index==1) matches a IP Address
if re.match(r'(\d+\.\d+\.\d+\.\d+)', _list[1]):
print("match:{}".format(_list[1]))
# End the loop
break
# Wait a second, before next try
time.sleep(1)
使用Python测试:3.4.2
答案 1 :(得分:0)
如果您使用的是Python 3.5或更高版本,则可以升级到具有一些有用功能的subprocess.run()
。
我还将考虑外壳程序和Awk管道。
addr = None
while True:
result = subprocess.run(
['kubectl', 'get', 'ing'],
stdout=subprocess,PIPE, stderr=subprocess.PIPE,
text=True, check=True)
lines = result.stdout.split('\n')
# [1:] - skip header line
# [:-1] - skip empty element after last newline
for line in lines[1:-1]:
# replace Awk
filelds = line.split()
if len(fields) > 2 and '.' in fields[2]:
addr = fields[2]
break
if addr:
break
time.sleep(1)
text=True
负责使用标准换行符将输出自动归一化为Unicode。 (在Python 3.7之前是universal_newlines=True
。)
答案 2 :(得分:0)
这是适用于Python(3.6)的可行解决方案:
addr = None
while addr is None:
out = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True)
print(out)
all_addr = out.decode().split('\n')
if re.match(r"\d+\.\d+\.\d+\.\d+", str(all_addr[1])):
addr = all_addr[1]
print('Address is: {}'.format(addr))
else:
addr = None