over-env/bin/timestamp-lines

33 lines
1 KiB
Python
Executable file

#! /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
)