Created
December 2, 2018 00:41
-
-
Save cemeyer/27ce5030008d97738f22e16fdc367984 to your computer and use it in GitHub Desktop.
[Unix] Hack: Change the error-handling on a file-like stream in Python3 (e.g., sys.stdout)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
# Re-opens the file-like stream of string 'attr' in parent object 'pobj' with | |
# the open() builtin parameters 'args' and 'kwargs'. Unix-specific. | |
# | |
# I would love it if there was a better way to do this and I just missed it. | |
def set_stream_errorh(pobj, attr, *args, **kwargs): | |
obj = getattr(pobj, attr) | |
fileno = obj.fileno() | |
# Keep the OS file handle alive by dup'ing the fd while we close the Python | |
# stream. | |
fd = os.dup(fileno) | |
assert fd >= 0 | |
obj.close() | |
obj = None | |
setattr(pobj, attr, None) | |
# dup2 it back into its previous number and reopen the stream with the | |
# error handling we wanted. | |
os.dup2(fd, fileno) | |
os.close(fd) | |
setattr(pobj, attr, os.fdopen(fileno, *args, **kwargs)) | |
... | |
# Ex: | |
set_stream_errorh(sys, "stdout", "w", encoding="utf-8", | |
errors="surrogateescape") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment