Python standard idiom to set sys.stdout buffer to zero doesn't work with Unicode

旧巷老猫 提交于 2019-12-05 08:42:44

The print function uses a special flag when writing to a file object, causing the PyFile_WriteObject function of the Python C API to retrieve the output encoding to do the unicode-to-bytes conversion, and by replacing the stdout stream you lost the encoding. Unfortunately, you cannot explicitly set it again:

encoding = sys.stdout.encoding
sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
sys.stdout.encoding = encoding  # Raises a TypeError; readonly attribute

You also cannot use the io.open function instead, since it doesn't allow buffering to be disabled if you want to be able to use the encoding option you'd require.

The proper way to have the print function flush immediately is to use the flush=True keyword:

print(something, flush=True)

If that's too tedious to add everywhere, consider using a custom print function:

def print(*args, **kw):
    flush = kw.pop('flush', True)  # Python 2.7 doesn't support the flush keyword..   
    __builtins__.print(*args, **kw)
    if flush:
        sys.stdout.flush()

Since Python 2.7's print() function doesn't actually support the flush keyword yet (botheration), you can simulate that by adding an explicit flush instead in that custom version.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!