From 005c83561d528c3bb2cf5a7341104909a0e36a96 Mon Sep 17 00:00:00 2001 From: Martin Sekera Date: Sun, 29 Sep 2024 10:45:25 +0200 Subject: [PATCH] Add timestamp-lines script to annotate lines with timestamps --- bin/timestamp-lines | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100755 bin/timestamp-lines diff --git a/bin/timestamp-lines b/bin/timestamp-lines new file mode 100755 index 0000000..150ee58 --- /dev/null +++ b/bin/timestamp-lines @@ -0,0 +1,33 @@ +#! /usr/bin/env python + +import argparse +import sys +import time + +def process_lines(in_file, out_file, fmt="%Y-%m-%d %H:%M:%S: "): + """ + Reads lines from a file-like object in_file, prefixes them + with a timestamp according to the provided format, + and writes them into the file-like object out_file. + + Typically in_file is stdin, out_file is stdout. + """ + + for line in in_file: + out_file.write(time.strftime(fmt, time.localtime()) + line) + out_file.flush() + +if __name__ == "__main__": + # parse command line args + parser = argparse.ArgumentParser(description="Annotate lines with timestamps") + parser.add_argument("-i", "--infile", help="Input file, defaults to stdin") + parser.add_argument("-o", "--outfile", help="Output file, defaults to stdout") + parser.add_argument("-f", "--format", help="Timestamp format (strftime style)", default="%Y-%m-%d %H:%M:%S: ") + args = parser.parse_args() + + # process lines + process_lines( + open(args.infile) if args.infile else sys.stdin, + open(args.outfile, "w") if args.outfile else sys.stdout, + args.format + )