Skip to content

Instantly share code, notes, and snippets.

@cemeyer
Created December 2, 2018 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cemeyer/27ce5030008d97738f22e16fdc367984 to your computer and use it in GitHub Desktop.
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)
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