11import os
22import sys
33
4- import sys
54from typing import Any , Dict
65
76# Avoid "LookupError: unknown encoding: ascii" when open() called in a destructor
87outnull_file = open (os .devnull , "w" )
98errnull_file = open (os .devnull , "w" )
109
10+ STDOUT_FILENO = 1
11+ STDERR_FILENO = 2
12+
1113class suppress_stdout_stderr (object ):
1214 # NOTE: these must be "saved" here to avoid exceptions when using
1315 # this context manager inside of a __del__ method
@@ -22,12 +24,8 @@ def __enter__(self):
2224 if self .disable :
2325 return self
2426
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 ()
27+ self .old_stdout_fileno_undup = STDOUT_FILENO
28+ self .old_stderr_fileno_undup = STDERR_FILENO
3129
3230 self .old_stdout_fileno = self .os .dup (self .old_stdout_fileno_undup )
3331 self .old_stderr_fileno = self .os .dup (self .old_stderr_fileno_undup )
@@ -47,15 +45,14 @@ def __exit__(self, *_):
4745 return
4846
4947 # 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
48+ self .sys .stdout = self .old_stdout
49+ self .sys .stderr = self .old_stderr
5350
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 )
51+ self .os .dup2 (self .old_stdout_fileno , self .old_stdout_fileno_undup )
52+ self .os .dup2 (self .old_stderr_fileno , self .old_stderr_fileno_undup )
5653
57- self .os .close (self .old_stdout_fileno )
58- self .os .close (self .old_stderr_fileno )
54+ self .os .close (self .old_stdout_fileno )
55+ self .os .close (self .old_stderr_fileno )
5956
6057
6158class MetaSingleton (type ):
0 commit comments