From 4673be40e5b69ca62ac9d202a0d87e2db07f42c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Barto=C5=A1?= Date: Thu, 30 Mar 2023 21:00:45 +0200 Subject: [PATCH] json_dump: Fixed output to stdout The last commit (ab713e0), which added the option to stream data over TCP, broke the default output to TCP (stdout.write only accepts str, not bytes). Moreover, it used an undocumented socket.SocketIO object, which is not the best idea. This implements the TCP stream differently and reverts the changes done to the other output options, so all output types now work. --- json_dump/json_dump.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/json_dump/json_dump.py b/json_dump/json_dump.py index ede48221..7fff8213 100755 --- a/json_dump/json_dump.py +++ b/json_dump/json_dump.py @@ -34,19 +34,24 @@ trap.init(["-i", options.ifcspec]) # Open output file -if options.filename and options.filename_append: - sys.stderr.write("Error: -w and -a are mutually exclusive.") +if (options.filename and options.filename_append or + options.filename and options.networktarget or + options.filename_append and options.networktarget): + sys.stderr.write("Error: -w, -a, -s are mutually exclusive.") sys.exit(1) if options.filename: - file = io.FileIO(options.filename, "w") + file = open(options.filename, "w", encoding="utf-8") elif options.filename_append: - file = io.FileIO(options.filename_append, "a") + file = open(options.filename_append, "a", encoding="utf-8") elif options.networktarget: - addr = options.networktarget.split(":") - if len(addr) != 2: - raise AttributeError("Malformed argument of -s host:port") - s = socket.create_connection((addr[0], int(addr[1]))) - file = socket.SocketIO(s, "w") + try: + addr, port = options.networktarget.split(":") + port = int(port) + except (TypeError, ValueError): + sys.stderr.write("Error: malformed argument of -s host:port") + sys.exit(1) + s = socket.create_connection((addr, port)) + file = s.makefile("w", encoding="utf-8") else: file = sys.stdout @@ -82,8 +87,8 @@ rec = json.loads(data.decode("utf-8")) if options.verbose: print("Message: {0}".format(rec)) - # Print it to file or stdout - file.write(bytes(json.dumps(rec, indent=options.indent) + '\n', "utf-8")) + # Print it to file, stdout, or send to socket + file.write(json.dumps(rec, indent=options.indent) + '\n') if not options.noflush: file.flush() except ValueError as e: