Skip to content

Commit 5b5bcc2

Browse files
Add logconvert script (#1072)
Co-authored-by: Felix Divo <[email protected]>
1 parent 48e9040 commit 5b5bcc2

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed

can/logconvert.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Convert a log file from one format to another.
3+
"""
4+
5+
import sys
6+
import argparse
7+
import errno
8+
9+
from can import LogReader, Logger, SizedRotatingLogger
10+
11+
12+
class ArgumentParser(argparse.ArgumentParser):
13+
def error(self, message):
14+
self.print_help(sys.stderr)
15+
self.exit(errno.EINVAL, "%s: error: %s\n" % (self.prog, message))
16+
17+
18+
def main():
19+
parser = ArgumentParser(
20+
description="Convert a log file from one format to another.",
21+
)
22+
23+
parser.add_argument(
24+
"-s",
25+
"--file_size",
26+
dest="file_size",
27+
type=int,
28+
help="Maximum file size in bytes. Rotate log file when size threshold is reached.",
29+
default=None,
30+
)
31+
32+
parser.add_argument(
33+
"input",
34+
metavar="INFILE",
35+
type=str,
36+
help="Input filename. The type is dependent on the suffix, see can.LogReader.",
37+
)
38+
39+
parser.add_argument(
40+
"output",
41+
metavar="OUTFILE",
42+
type=str,
43+
help="Output filename. The type is dependent on the suffix, see can.Logger.",
44+
)
45+
46+
args = parser.parse_args()
47+
48+
with LogReader(args.input) as reader:
49+
50+
if args.file_size:
51+
logger = SizedRotatingLogger(
52+
base_filename=args.output, max_bytes=args.file_size
53+
)
54+
else:
55+
logger = Logger(filename=args.output)
56+
57+
with logger:
58+
try:
59+
for m in reader: # pylint: disable=not-an-iterable
60+
logger(m)
61+
except KeyboardInterrupt:
62+
sys.exit(1)
63+
64+
65+
if __name__ == "__main__":
66+
main()

scripts/can_logconvert.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
See :mod:`can.logconvert`.
5+
"""
6+
7+
from can.logconvert import main
8+
9+
10+
if __name__ == "__main__":
11+
main()

test/test_scripts.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,22 @@ def _import(self):
103103
return module
104104

105105

106+
class TestLogconvertScript(CanScriptTest):
107+
def _commands(self):
108+
commands = [
109+
"python -m can.logconvert --help",
110+
"python scripts/can_logconvert.py --help",
111+
]
112+
if IS_UNIX:
113+
commands += ["can_logconvert.py --help"]
114+
return commands
115+
116+
def _import(self):
117+
import can.logconvert as module
118+
119+
return module
120+
121+
106122
# TODO add #390
107123

108124

0 commit comments

Comments
 (0)