44import sys
55from typing import Any , Dict
66
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" )
7+ class NullDevice ():
8+ def write ( self , s ):
9+ pass
1010
1111class suppress_stdout_stderr (object ):
1212 # NOTE: these must be "saved" here to avoid exceptions when using
@@ -21,41 +21,19 @@ 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-
3524 self .old_stdout = self .sys .stdout
3625 self .old_stderr = self .sys .stderr
3726
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
27+ self .sys .stdout = NullDevice ()
28+ self .sys .stderr = NullDevice ()
4329 return self
4430
4531 def __exit__ (self , * _ ):
4632 if self .disable :
4733 return
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 )
34+
35+ self .sys .stdout = self .old_stdout
36+ self .sys .stderr = self .old_stderr
5937
6038
6139class MetaSingleton (type ):
0 commit comments