我需要输出一些字符串(到stdout),因为windows控制台在cp437中工作,如果字符串包含cp437之外的任何字符,就会抛出异常。
我绕过了这个
encoding=sys.stdout.encoding
pathstr = path.encode(encoding,errors="replace").decode(encoding)
print(pathstr)
其中
path
是我要输出的str
。我可以用“?”代替字符这看起来不太好,因为它会转换成字节数组并返回到str。
有没有更好的方法来实现这个目标?
我还是python新手(可能一周),我在cpython 3.3中使用Win7 32位
最佳答案
这看起来不太好,因为它会转换成字节数组并返回到str。
如果要将原始字节写入流,请使用.buffer
:
pathbytes= path.encode(encoding, errors= 'replace')
sys.stdout.buffer.write(pathbytes)
…噢,当issue 1602出现问题时,我们可以避免Windows命令提示符的Unicode恐怖。。。