[Tutor] UnicodeEncodeError in python

Peter Otten __peter__ at web.de
Thu Sep 11 23:18:54 CEST 2014


Juan Christian wrote:

> On Thu, Sep 11, 2014 at 5:23 PM, Peter Otten <__peter__ at web.de> wrote:
>>
>>
>> You are getting an *encoding* error, so this may be triggered when you
>> are trying to print. Can you post the traceback?
>>
>> Also, what is your OS and what does
>>
>> $ python3 -c'import locale; print(locale.getpreferredencoding())'
>> UTF-8
>>
>> show?
> 
> 
> Show: cp1252
> 
> PS D:\Documents\HomeBroker> py .\main.py
> ['O Deputado Jovem', 'Bob Swaget', 'Baldrick', 'Inigo the brave',
> 'KeplerBR', 'Lastemp3ror', 'Amethyst', 'wildee14', 'Le
>  Monade']
> Traceback (most recent call last):
>   File ".\main.py", line 11, in <module>
>     search(my_u[0])
>   File ".\main.py", line 8, in search
>     search(current)
>   File ".\main.py", line 5, in search
>     print([user.persona_name for user in x.get_friend_list()])
>   File "C:\Development\Languages\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 '\u262d' in
> position 322: character maps to <undefined>

You can advise python to print \u262d or similar for codepoints that cannot 
be represented in cp1252 by setting the environment variable

PYTHONIOENCODING=cp1252:backslashreplace

Alternatively you can wrap stdout inside your script with something like

sys.stdout = codecs.getwriter(sys.stdout.encoding)(
    sys.stdout.buffer, "backslashreplace")

PS: There may also be a way to configure the console to accept a larger 
charset, but I'm not a Windows and cannot help you with that.




More information about the Tutor mailing list