forked from scmschmidt/cgar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cgar_csv2table
executable file
·186 lines (145 loc) · 6.41 KB
/
cgar_csv2table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
cgar_csv2table
Reads a CVS file created by `cgar_log2csv` and prints the data as table to stdout.
Ideas/ToDos:
-----------
- Implement filtering by start and end time.
Changelog:
----------
08.02.2023 v0.1 - first release
09.02.2023 v0.2 - code cleaning
- table can now splitted into two lines (cgroup and attribute)
to save space and increase readability
"""
import argparse
import datetime
import os
import sys
__version__ = '0.2'
def argument_parse():
"""Evaluates the command line arguments."""
# All supported attributes (with and without their sub keys).
parser = argparse. ArgumentParser(prog=os.path.basename(sys.argv[0]),
description='Reads a CVS file created by `cgar_log2csv` and prints the data as table to stdout.',
add_help=True,
epilog=f'v{__version__}')
# Global flags and arguments.
# parser.add_argument('--start-time',
# metavar='TIME',
# dest='start_time',
# type=str,
# action='store',
# required=False,
# help='only print data from this time forward (no timezone info)')
# parser.add_argument('--end-time',
# metavar='TIME',
# dest='end_time',
# type=str,
# action='store',
# required=False,
# help='only print data to this time (no timezone info)')
parser.add_argument('-s', '--separator',
dest='separator',
type=str,
action='store',
default=',',
required=False,
help='separator used in the CSV file (default: ,)')
parser.add_argument('-l', '--remove-level',
dest='remove_level',
action='store',
type=int,
choices=range(0,10),
default=0,
required=False,
help='amount of directory levels removed from cgroup path for output (default: 0)')
parser.add_argument('csvfile',
metavar='CSVFILE',
type=str,
help='the CSV file'),
args = parser.parse_args()
# Convert times into datetime objects
# try:
# args.time_range = (
# datetime.datetime.strptime(args.start_time, '%Y-%m-%dT%H:%M:%S') if args.start_time else None,
# datetime.datetime.strptime(args.end_time, '%Y-%m-%dT%H:%M:%S') if args.end_time else None)
# except Exception as err:
# print(f'Error in time range: {err}')
# sys.exit(1)
# Check if the CSV file is available.
if not os.path.isfile(args.csvfile) and os.access(args.csvfile, os.R_OK):
print(f'Logfile "{args.csvfile}" does not exists!')
sys.exit(0)
return args
def get_csv_line(filename: str) -> str:
"""Generator to walk through the given file."""
try:
with open(filename, 'r') as f:
for line in f:
yield line
except Exception as err:
print(f'Error reading the CSV file: {err}')
sys.exit(2)
def split_csv_line(line: str, separator: str) -> list:
"""Splits a CSV line into a list of cleaned fields."""
return [x.strip('\n\t "') for x in line.split(separator)]
def length_of_line(line: str, separator: str) -> list:
"""Gets a CSV line and returns a list with the length of each field."""
return [len(col) for col in split_csv_line(line ,separator)]
def print_table_line(fields: list, alignment:str, widths: list) -> None:
"""Prints the line formatted on stdout."""
for ix, col in enumerate(fields):
print(f'''{col:{alignment}{widths[ix]}} ''',end='')
print()
def main():
# Parse command line arguments.
arguments = argument_parse()
try:
# The generator for pre-reading the CSV file.
csv_file = get_csv_line(arguments.csvfile)
# Do a pre-parsing of the CSV file to get the width of each column.
# We also build the header, which gets transformed into two lines (cgroup and attribute)
# to save space and increase readability.
header = [[],[]]
for field in split_csv_line(next(csv_file), arguments.separator):
if '/' in field:
level = min(arguments.remove_level, field.count('/'))
field = '/'.join(field.split('/')[level:])
if '::' in field:
one, two = field.split('::', maxsplit=1)
header[0].append(one)
header[1].append(two)
else:
header[0].append(field)
header[1].append('')
column_width = [max(x) for x in zip([len(col) for col in header[0]], [len(col) for col in header[1]])]
for line in csv_file:
for ix, length in enumerate(length_of_line(line, arguments.separator)):
try:
column_width[ix] = max(column_width[ix], length)
except IndexError:
column_width.append(length)
# Print the prepared header first.
print_table_line(header[0], '^', column_width)
print_table_line(header[1], '^', column_width)
print(' '.join(['-' * l for l in column_width]))
# Walk trough the CSV file and print each line nicely.
# The first line we drop, because we have printed the header already.
csv_file = get_csv_line(arguments.csvfile)
next(csv_file)
for line in csv_file:
print_table_line(split_csv_line(line, arguments.separator), '>', column_width)
except (BrokenPipeError, IOError):
# Handle BrokenPipe issue: https://docs.python.org/3/library/signal.html#note-on-sigpipe
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
sys.exit(0)
except Exception as err:
print(f'Sadly a runtime error ocurred: {err}')
sys.exit(3)
# Bye.
sys.exit(0)
if __name__ == "__main__":
main()