What I'm trying to do is print utf-8 card symbols (?,?,?,?) from a python module to a windows console
UTF-8 is a byte encoding of Unicode characters. ???? are Unicode characters which can be reproduced in a variety of encodings and UTF-8 is one of those encodings—as a UTF, UTF-8 can reproduce any Unicode character. But there is nothing specifically “UTF-8” about those characters.
Other encodings that can reproduce the characters ???? are Windows code page 850 and 437, which your console is likely to be using under a Western European install of Windows. You can print ? in these encodings but you are not using UTF-8 to do so, and you won't be able to use other Unicode characters that are available in UTF-8 but outside the scope of these code pages.
print(u'?')
UnicodeEncodeError: 'charmap' codec can't encode character 'u2660'
In Python 3 this is the same as the print('?')
test you did above, so there is something different about how you are invoking the script containing this print
, compared to your py -3.4
. What does sys.stdout.encoding
give you from the script?
To get print
working correctly you would have to make sure Python picks up the right encoding. If it is not doing that adequately from the terminal settings you would indeed have to set PYTHONIOENCODING
to cp437
.
>>> text = '?'
>>> print(text.encode('utf-8'))
b'xe2x99xa0'
print
can only print Unicode strings. For other types including the bytes
string that results from the encode()
method, it gets the literal representation (repr
) of the object. b'xe2x99xa0'
is how you would write a Python 3 bytes literal containing a UTF-8 encoded ?.
If what you want to do is bypass print
's implicit encoding to PYTHONIOENCODING and substitute your own, you can do that explicitly:
>>> import sys
>>> sys.stdout.buffer.write('?'.encode('cp437'))
This will of course generate wrong output for any consoles not running code page 437 (eg non-Western-European installs). Generally, for apps using the C stdio, like Python does, getting non-ASCII characters to the Windows console is just too unreliable to bother with.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…