1
1
import os
2
2
import sys
3
3
4
- import sys
5
4
from typing import Any , Dict
6
5
7
6
# Avoid "LookupError: unknown encoding: ascii" when open() called in a destructor
8
7
outnull_file = open (os .devnull , "w" )
9
8
errnull_file = open (os .devnull , "w" )
10
9
10
+ STDOUT_FILENO = 1
11
+ STDERR_FILENO = 2
12
+
11
13
class suppress_stdout_stderr (object ):
12
14
# NOTE: these must be "saved" here to avoid exceptions when using
13
15
# this context manager inside of a __del__ method
@@ -22,12 +24,8 @@ def __enter__(self):
22
24
if self .disable :
23
25
return self
24
26
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
31
29
32
30
self .old_stdout_fileno = self .os .dup (self .old_stdout_fileno_undup )
33
31
self .old_stderr_fileno = self .os .dup (self .old_stderr_fileno_undup )
@@ -47,15 +45,14 @@ def __exit__(self, *_):
47
45
return
48
46
49
47
# 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
53
50
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 )
56
53
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 )
59
56
60
57
61
58
class MetaSingleton (type ):
0 commit comments