44import sys
55from typing import Any , Dict
66
7- class NullDevice ():
8- def write ( self , s ):
9- pass
7+ # Avoid "LookupError: unknown encoding: ascii" when open() called in a destructor
8+ outnull_file = open ( os . devnull , "w" )
9+ errnull_file = open ( os . devnull , "w" )
1010
1111class suppress_stdout_stderr (object ):
1212 # NOTE: these must be "saved" here to avoid exceptions when using
@@ -21,19 +21,41 @@ def __init__(self, disable: bool = True):
2121 def __enter__ (self ):
2222 if self .disable :
2323 return self
24+
25+ # Check if sys.stdout and sys.stderr have fileno method
26+ if not hasattr (self .sys .stdout , 'fileno' ) or not hasattr (self .sys .stderr , 'fileno' ):
27+ return self # Return the instance without making changes
28+
29+ self .old_stdout_fileno_undup = self .sys .stdout .fileno ()
30+ self .old_stderr_fileno_undup = self .sys .stderr .fileno ()
31+
32+ self .old_stdout_fileno = self .os .dup (self .old_stdout_fileno_undup )
33+ self .old_stderr_fileno = self .os .dup (self .old_stderr_fileno_undup )
34+
2435 self .old_stdout = self .sys .stdout
2536 self .old_stderr = self .sys .stderr
2637
27- self .sys .stdout = NullDevice ()
28- self .sys .stderr = NullDevice ()
38+ self .os .dup2 (outnull_file .fileno (), self .old_stdout_fileno_undup )
39+ self .os .dup2 (errnull_file .fileno (), self .old_stderr_fileno_undup )
40+
41+ self .sys .stdout = outnull_file
42+ self .sys .stderr = errnull_file
2943 return self
3044
3145 def __exit__ (self , * _ ):
3246 if self .disable :
3347 return
34-
35- self .sys .stdout = self .old_stdout
36- self .sys .stderr = self .old_stderr
48+
49+ # Check if sys.stdout and sys.stderr have fileno method
50+ if hasattr (self .sys .stdout , 'fileno' ) and hasattr (self .sys .stderr , 'fileno' ):
51+ self .sys .stdout = self .old_stdout
52+ self .sys .stderr = self .old_stderr
53+
54+ self .os .dup2 (self .old_stdout_fileno , self .old_stdout_fileno_undup )
55+ self .os .dup2 (self .old_stderr_fileno , self .old_stderr_fileno_undup )
56+
57+ self .os .close (self .old_stdout_fileno )
58+ self .os .close (self .old_stderr_fileno )
3759
3860
3961class MetaSingleton (type ):
0 commit comments