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

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

问题描述

好的,我想在我的 windows xp 控制台中打印一个字符串.控制台无法打印几个字符,因此我必须编码到我的 stdout.encoding 中,即cp437".但是打印编码的字符串时,'ß' 被打印为 '\xe1'.解码回unicode并打印字符串后,我得到了我想要的输出.但这感觉有点不对.打印字符串并获取的正确方法是什么?对于不可打印的字符?

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 ? gro\xe1es'
>>>print(var.encode('cp437', 'replace'))
b'Bla ? gro\xe1es'

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

@Mark Ransom:因为我打印了很多,所以我觉得代码很臃肿:/

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

@eryksun:正是我要找的.非常感谢!

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

推荐答案

另一种解决方案是不使用残缺的 Windows 控制台进行常规 unicode 输出.Tk 文本小部件(作为 tkinter 文本实例访问)处理所有 BMP 字符,只要所选字体将.

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.

由于 Idle 使用了 tkinter,所以它也可以.运行包含

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

print('Bla \u2013 großes')

在 Shell 窗口中打印以下内容.

prints the following in the Shell window.

Bla – großes

可以使用 -m 和 -r 从控制台通过 Idle 运行文件.

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

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

这会打开一个 shell 窗口并打印与上面相同的内容.或者您可以使用标签或文本小部件创建自己的 tk 窗口.

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天全站免登陆