使用Python 2.7.9在PyWinUSB中使用UnicodeEncodeError?

时间:2015-05-16 15:27:24

标签: python python-2.7 pywinusb

所以,我正在尝试使用PyWinUSB,但我不能走得太远因为我不断得到UnicodeEncodeError

代码:

import pywinusb.hid as hid
hid.find_all_hid_devices()

输出:

[Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 91: ordinal not in range(128)

请注意,这只会在我插入外接键盘和鼠标时发生(这是Microsoft无线组合)。

当我尝试相同的代码时,这就是我在Python 3.4中得到的。

HID device (vID=0x045e, pID=0x00e3, v=0x0053); Microsft; Microsoft Wireless Optical Desktop\xae 2.20, Path: \\?\hid#vid_045e&pid_00e3&mi_01&col01#8&a279d5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}  
HID device (vID=0x045e, pID=0x00e3, v=0x0053); Microsft; Microsoft Wireless Optical Desktop\xae 2.20, Path: \\?\hid#vid_045e&pid_00e3&mi_01&col03#8&a279d5&0&0002#{4d1e55b2-f16f-11cf-88cb-001111000030}  
HID device (vID=0x045e, pID=0x00e3, v=0x0053); Microsft; Microsoft Wireless Optical Desktop\xae 2.20, Path: \\?\hid#vid_045e&pid_00e3&mi_01&col04#8&a279d5&0&0003#{4d1e55b2-f16f-11cf-88cb-001111000030}

但是,如果我尝试使用Python 3.4为每个项目执行print,我会得到:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python34\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xae' in position 91: character maps to <undefined>

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

这不是pyWinUsb问题,它实际上是Python 2.x上的设计问题。

默认情况下,stdout写入时没有字符解码管理。

USB设备字符串是Unicode UTF-8编码,因此安装字符解码器是安全的(来自pyWinUsb show_hids.py示例):

if sys.version_info < (3,): import codecs output = codecs.getwriter('mbcs')(sys.stdout) else: # python3, you have to deal with encodings, try redirecting to any file output = sys.stdout