Try the following before writing anything:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
If you only want to change to binary mode temporarily, you can write yourself a wrapper:
import sys
from contextlib import contextmanager
@contextmanager
def binary_mode(f):
if sys.platform != "win32":
yield; return
import msvcrt, os
def setmode(mode):
f.flush()
msvcrt.setmode(f.fileno(), mode)
setmode(os.O_BINARY)
try:
yield
finally:
setmode(os.O_TEXT)
with binary_mode(sys.stdout), binary_mode(sys.stderr):
# code
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…