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