python3打印unicode到windows xp控制台编码cp437 [英] python3 print unicode to windows xp console encode cp437

查看:31
本文介绍了python3打印unicode到windows xp控制台编码cp437的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ok, i want to print a string in my windows xp console. There are several characters the console cant print, so i have to encode to my stdout.encoding which is 'cp437'. but printing the encoded string, the 'ß' is printed as 'xe1'. after decoding back to unicode and printing the string, i get the output i want. but this feels somewhat wrong. how is the correct way to print a string and get ? for non-printable characters?

>>>var
'Bla u2013 großes'
>>>print(var)
UnicodeEncodeError: 'charmap' codec can't encode character 'u2013'

>>>var.encode('cp437', 'replace')
b'Bla ? groxe1es'
>>>print(var.encode('cp437', 'replace'))
b'Bla ? groxe1es'

>>>var.encode('cp437', 'replace').decode('cp437')
'Bla ? großes'
>>>print(var.encode('cp437', 'replace').decode('cp437'))
Bla ? großes

edit: @Mark Ransom: since i print a lot this makes the code pretty bloated i feel :/

@eryksun: excactly what i was looking for. thanks a lot!

解决方案

An alternate solution is to not use the crippled Windows console for general unicode output. Tk text widgets (accessed as tkinter Text instances) handle all BMP chars as long as the selected font will.

Since Idle used tkinter, it can as well. Running an Idle editor file (call it tem.py) containing

print('Bla u2013 großes')

prints the following in the Shell window.

Bla – großes

A file can be run through Idle from the console with -m and -r.

C:>python -m idlelib -r c:/programs/python34/tem.py

This opens a shell window and prints the same as above. Or you can create your own tk window with Label or Text widget.

这篇关于python3打印unicode到windows xp控制台编码cp437的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆