From 9d1c0bce1ac11a8769076297df256d2dfd250316 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Mon, 27 May 2024 16:01:11 +1200 Subject: [PATCH] force python to immediatly flush stdout and stderr streams so other programs such as nodejs can use immediately --- src/__init__.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/__init__.py diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..24b56e9 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,30 @@ +import sys + +# NOTE: this class is required to be able to use print/log commands and have them flush to stdout and stderr immediately +# without wrapper stdout and stderr, when using `childProcess.stdout.on('data', ...)` in NodeJS script, we never get +# any events fired until the process exists. However, force flushing the streams does first the callbacks in NodeJS. + + +# this class forces stream writes to be flushed immediately +class ImmediateFlushingStreamWrapper: + + def __init__(self, stream): + self.stream = stream + + # force write to flush immediately + def write(self, data): + self.stream.write(data) + self.stream.flush() + + # force writelines to flush immediately + def writelines(self, lines): + self.stream.writelines(lines) + self.stream.flush() + + def __getattr__(self, attr): + return getattr(self.stream, attr) + + +# wrap stdout and stderr with our custom wrapper +sys.stdout = ImmediateFlushingStreamWrapper(sys.stdout) +sys.stderr = ImmediateFlushingStreamWrapper(sys.stderr)