2023-07-28 18:45:18 +00:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
|
|
class suppress_stdout_stderr(object):
|
2023-11-02 19:30:55 +00:00
|
|
|
# NOTE: these must be "saved" here to avoid exceptions when using
|
|
|
|
# this context manager inside of a __del__ method
|
|
|
|
open = open
|
|
|
|
sys = sys
|
|
|
|
os = os
|
|
|
|
|
2023-11-03 17:02:15 +00:00
|
|
|
def __init__(self, disable: bool = True):
|
|
|
|
self.disable = disable
|
|
|
|
|
2023-07-28 18:45:18 +00:00
|
|
|
# Oddly enough this works better than the contextlib version
|
|
|
|
def __enter__(self):
|
2023-11-03 17:02:15 +00:00
|
|
|
if self.disable:
|
|
|
|
return self
|
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.outnull_file = self.open(self.os.devnull, "w")
|
|
|
|
self.errnull_file = self.open(self.os.devnull, "w")
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.old_stdout_fileno_undup = self.sys.stdout.fileno()
|
|
|
|
self.old_stderr_fileno_undup = self.sys.stderr.fileno()
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.old_stdout_fileno = self.os.dup(self.sys.stdout.fileno())
|
|
|
|
self.old_stderr_fileno = self.os.dup(self.sys.stderr.fileno())
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.old_stdout = self.sys.stdout
|
|
|
|
self.old_stderr = self.sys.stderr
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.os.dup2(self.outnull_file.fileno(), self.old_stdout_fileno_undup)
|
|
|
|
self.os.dup2(self.errnull_file.fileno(), self.old_stderr_fileno_undup)
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.sys.stdout = self.outnull_file
|
|
|
|
self.sys.stderr = self.errnull_file
|
2023-07-28 18:45:18 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, *_):
|
2023-11-03 17:02:15 +00:00
|
|
|
if self.disable:
|
|
|
|
return
|
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.sys.stdout = self.old_stdout
|
|
|
|
self.sys.stderr = self.old_stderr
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.os.dup2(self.old_stdout_fileno, self.old_stdout_fileno_undup)
|
|
|
|
self.os.dup2(self.old_stderr_fileno, self.old_stderr_fileno_undup)
|
2023-07-28 18:45:18 +00:00
|
|
|
|
2023-11-02 19:30:55 +00:00
|
|
|
self.os.close(self.old_stdout_fileno)
|
|
|
|
self.os.close(self.old_stderr_fileno)
|
2023-07-28 18:45:18 +00:00
|
|
|
|
|
|
|
self.outnull_file.close()
|
|
|
|
self.errnull_file.close()
|