Reputation: 1079
This is my python code. In this code, the str1 field contains the output of the user command (w). The last field(WHAT) can contain one or more spaces. I am trying to create a list from the output of the command (w).
Issue: In the 2nd row, FROM field does not contain any value due to that I am not getting the expected output. If it(FROM field) contains any value, then I am getting the expected output.
Code:
import re
lista, listb, list_final =[],[],[]
str1 = '''17:36:34 up 17 days, 1:48, 3 users, load average: 6.33, 5.37, 5.46
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
Arul abc/0 10.XXX.XX.X1 14:41 2:31m 2.04s 1.97s ssh [email protected]
Peter abc/1 17:36 1.00s 0.08s 0.02s w
Joe abc/3 10.XXX.XX.X3 13:59 2:41m 4:38 0.08s /opt/ google / chrome/chrome'''
str1 = re.sub(' +', ' ', str1)
lista = str1.splitlines ()
lista = lista[2:]
listb=[re.split(" ", el, maxsplit=7) for el in lista]
print (listb)
The above code produce the result as below Result:
[['Arul', 'abc/0', '10.XXX.XX.X1', '14:41', '2:31m', '2.04s', '1.97s', 'ssh [email protected]'],
['Peter', 'abc/1', '17:36', '1.00s', '0.08s', '0.02s', 'w'],
['Joe', 'abc/3', '10.XXX.XX.X3', '13:59', '2:41m', '4:38', '0.08s', '/opt/ google / chrome/chrome']]
I am expecting the result as below. (if any of the field (FROM) contains a null value, the same should be populated in the list output.
Expected result:
[['Arul', 'abc/0', '10.XXX.XX.X1', '14:41', '2:31m', '2.04s', '1.97s', 'ssh [email protected]'],
['Peter', 'abc/1', ' ', '17:36', '1.00s', '0.08s', '0.02s', 'w'],
['Joe', 'abc/3', '10.XXX.XX.X3', '13:59', '2:41m', '4:38', '0.08s', '/opt/ google / chrome/chrome']]
Upvotes: 0
Views: 68
Reputation: 1917
lista, listb, list_final = [], [], []
str1 = '''17:36:34 up 17 days, 1:48, 3 users, load average: 6.33, 5.37, 5.46
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
Arul abc/0 10.XXX.XX.X1 14:41 2:31m 2.04s 1.97s ssh [email protected]
Peter abc/1 17:36 1.00s 0.08s 0.02s w
Joe abc/3 10.XXX.XX.X3 13:59 2:41m 4:38 0.08s /opt/ google / chrome/chrome'''
lista = str1.splitlines()
first_row = lista[1]
indices = [first_row.index(x) for x in first_row.split()]
lista = lista[2:]
lines_splitted = []
#split according to first line
for line in lista:
l = []
for i in range(0, len(indices) - 1):
l.append(line[indices[i]:indices[i + 1]])
l.append(line[indices[-1]:])
lines_splitted.append(l)
# adjust whitespaces
for index in range(0, 8):
for line_splitted in lines_splitted:
if line_splitted[index].isspace():
lengths = [len(x[index].strip()) for x in lines_splitted]
max_length = max(lengths)
line_splitted[index] = line_splitted[index].strip() + ' ' * max_length
# remove others whitespaces
for index in range(0, 8):
for line_splitted in lines_splitted:
if not line_splitted[index].isspace():
line_splitted[index] = line_splitted[index].strip()
print(*lines_splitted, sep='\n')
Upvotes: 1