def silence_streams(func):
def wrapper(*args, **kwargs):
# save stderr
save_streams = sys.__stderr__
save_streams.flush()
# file descriptor for stderr is 2
save_stderr = os.dup(2)
# silence
null_fd = os.open(os.devnull, os.O_RDWR)
os.dup2(null_fd, 2)
# uncomment the line to test if stderr is silenced
# 1/0
try:
bak_file_path = func(*args, **kwargs)
sys.stderr = save_streams
os.dup2(save_stderr, 2)
return bak_file_path
except:
sys.stderr = save_streams
os.dup2(save_stderr, 2)
return wrapper
评论列表
文章目录