4
4
import sys
5
5
from typing import Any , Dict
6
6
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
10
10
11
11
class suppress_stdout_stderr (object ):
12
12
# NOTE: these must be "saved" here to avoid exceptions when using
@@ -21,41 +21,19 @@ def __init__(self, disable: bool = True):
21
21
def __enter__ (self ):
22
22
if self .disable :
23
23
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
-
35
24
self .old_stdout = self .sys .stdout
36
25
self .old_stderr = self .sys .stderr
37
26
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 ()
43
29
return self
44
30
45
31
def __exit__ (self , * _ ):
46
32
if self .disable :
47
33
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
59
37
60
38
61
39
class MetaSingleton (type ):
0 commit comments