From: Michael Orlitzky Date: Thu, 22 Sep 2022 01:21:08 +0000 (-0400) Subject: djbdns/io.py: use Popen's context manager to clean up. X-Git-Tag: 0.0.1~11 X-Git-Url: http://gitweb.michael.orlitzky.com/?p=djbdns-logparse.git;a=commitdiff_plain;h=c965f2fea1788a7faba2c67a4f05c27d5c34373b djbdns/io.py: use Popen's context manager to clean up. --- diff --git a/djbdns/io.py b/djbdns/io.py index 1d68fac..75422c0 100644 --- a/djbdns/io.py +++ b/djbdns/io.py @@ -31,25 +31,26 @@ def parse_logfile(file : TextIO): # Open a pipe to tai64nlocal. We'll write lines of our input file # (the log file) to it, and read back the same lines but with # friendly timestamps in them. - tai = Popen(["tai64nlocal"], stdin=PIPE, stdout=PIPE, text=True, bufsize=0) + with Popen(["tai64nlocal"], + stdin=PIPE, + stdout=PIPE, + text=True, + bufsize=0) as tai: - for line in file: - tai.stdin.write(line) - line = tai.stdout.readline() + for line in file: + tai.stdin.write(line) + line = tai.stdout.readline() - friendly_line = handle_tinydns_log(line) - if not friendly_line: - friendly_line = handle_dnscache_log(line) + friendly_line = handle_tinydns_log(line) if not friendly_line: - friendly_line = line - - try: - print(friendly_line) - except BrokenPipeError: - # If our stdout is being piped to another process and if - # that process closes the pipe, this error will be raised - # the next time we try to write to stdout. - break - - # Ensure that the pipe gets closed. - tai.communicate() + friendly_line = handle_dnscache_log(line) + if not friendly_line: + friendly_line = line + + try: + print(friendly_line) + except BrokenPipeError: + # If our stdout is being piped to another process and if + # that process closes the pipe, this error will be raised + # the next time we try to write to stdout. + break