MuteStdIO: Partly support ctor arguments

ctor now understands stdio='off' or ='something' and mutes stdout in the
first case.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2017-07-26 11:38:38 +02:00
commit 3451ea0d83

View file

@ -7,30 +7,35 @@ from fcntl import fcntl, F_GETFL, F_SETFL
class MuteStdIO: # export class MuteStdIO: # export
def __init__(self, mute_stderr=False, mute_stdout=True): def __init__(self, stderr='on', stdout='off'):
# TODO: arguments not implemented self.__stderr = stderr
self.__stdout = stdout
# TODO: arguments not fully implemented,
# Add support for 'off', 'on', 'stdxxx' (redirection)
pass pass
def __enter__(self): def __enter__(self):
rfd, wfd = os.pipe() if self.__stdout == 'off':
flags = fcntl(rfd, F_GETFL) rfd, wfd = os.pipe()
fcntl(rfd, F_SETFL, flags | os.O_NONBLOCK) flags = fcntl(rfd, F_GETFL)
self.rfile = io.open(rfd, 'r') fcntl(rfd, F_SETFL, flags | os.O_NONBLOCK)
self.fake_stdout_stream = io.open(wfd, 'w') self.rfile = io.open(rfd, 'r')
self.real_stdout_fd = os.dup(1) self.fake_stdout_stream = io.open(wfd, 'w')
#os.close(1) self.real_stdout_fd = os.dup(1)
os.dup2(wfd, 1) #os.close(1)
os.dup2(wfd, 1)
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
sys.stdout.flush() if self.__stdout == 'off':
os.dup2(self.real_stdout_fd, 1) sys.stdout.flush()
if type is not None: os.dup2(self.real_stdout_fd, 1)
#print("-------- Error while stdio was suppressed --------") if type is not None:
#traceback.print_stack() #print("-------- Error while stdio was suppressed --------")
#print(traceback) #traceback.print_stack()
print("-------- Captured output --------") #print(traceback)
print(*self.rfile.readlines()) print("-------- Captured output --------")
self.rfile.close() print(*self.rfile.readlines())
#print('type = ' + str(type)) self.rfile.close()
#print('value = ' + str(value)) #print('type = ' + str(type))
raise type(value) #print('value = ' + str(value))
raise type(value)