Python, 유니 코드 및 Windows 콘솔
Windows 콘솔에서 유니 코드 문자열을 인쇄하려고하면 UnicodeEncodeError: 'charmap' codec can't encode character ....
오류가 발생합니다. Windows 콘솔은 유니 코드 전용 문자를 허용하지 않기 때문이라고 생각합니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까? ?
이 상황에서 Python이 자동으로 인쇄하는 대신 실패 하게 만드는 방법 이 있습니까?
편집 : Python 2.5를 사용하고 있습니다.
참고 : 체크 표시가있는 @ LasseV.Karlsen 답변은 오래된 것입니다 (2008 년부터). 아래의 솔루션 / 응답 / 제안을주의해서 사용하십시오 !!
@JFSebastian의 답변 은 오늘 (2016 년 1 월 6 일)보다 관련성이 높습니다 .
참고 : 이 답변은 구식입니다 (2008 년부터). 아래 솔루션을주의해서 사용하십시오 !!
다음은 문제와 해결책을 자세히 설명하는 페이지입니다 ( rap.sys.stdout 텍스트를 인스턴스로 랩핑 하는 페이지 검색 ).
해당 페이지에서 발췌 한 코드는 다음과 같습니다.
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line'
UTF-8
<type 'unicode'> 2
Б
Б
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line' | cat
None
<type 'unicode'> 2
Б
Б
그 페이지에 더 많은 정보가 있으며 읽을 가치가 있습니다.
업데이트 : 파이썬 3.6 구현의 PEP 528 : UTF-8로 변경 Windows 콘솔 인코딩 : Windows에서 기본 콘솔은 이제 모든 유니 코드 문자를 사용할 수 있습니다. 내부적으로는 같은 유니 코드 API 사용 아래에 언급 된 패키지를 . 지금 작동해야합니다.win-unicode-console
print(unicode_string)
내가 얻을
UnicodeEncodeError: 'charmap' codec can't encode character...
오류입니다.
이 오류는 인쇄하려는 유니 코드 문자를 현재 ( chcp
) 콘솔 문자 인코딩 으로 표현할 수 없음을 의미합니다 . 코드 페이지는 종종 cp437
~ 1M 유니 코드 문자에서 ~ 0x100 문자 만 나타낼 수있는 8 비트 인코딩입니다 .
>>> u "\ N {EURO SIGN}". encode ( 'cp437') 역 추적 (가장 최근 통화) : ... UnicodeEncodeError : 'charmap'코덱은 위치 0에서 '\ u20ac'문자를 인코딩 할 수 없습니다. 캐릭터는
Windows 콘솔은 유니 코드 전용 문자를 허용하지 않기 때문이라고 생각합니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?
Windows 콘솔은 유니 코드 문자를 허용 하며 해당 글꼴이 구성된 경우 해당 문자를 표시 할 수도 있습니다 (BMP 만 해당) . @Daira Hopwood의 답변WriteConsoleW()
에서 제안한대로 API를 사용해야합니다 . 패키지를 투명하게 호출 할 수 있습니다. 즉, package 를 사용하는 경우 스크립트를 수정하지 않아도됩니다 .win-unicode-console
T:\> py -mpip install win-unicode-console
T:\> py -mrun your_script.py
Python 3.4, 유니 코드, 다른 언어 및 Windows와의 관계는 무엇입니까?를 참조하십시오 .
?
이 상황에서 Python이 자동으로 인쇄하는 대신 실패 하게 만드는 방법 이 있습니까?
?
귀하의 경우에 모든 불가피한 문자를 대체하는 것으로 충분하다면 envvar을 설정할 수 PYTHONIOENCODING
있습니다 :
T:\> set PYTHONIOENCODING=:replace
T:\> python3 -c "print(u'[\N{EURO SIGN}]')"
[?]
Python 3.6 이상에서는 envvar가 비어 있지 않은 문자열로 설정되어 PYTHONIOENCODING
있지 않으면 대화식 콘솔 버퍼에 대해 envvar로 지정된 인코딩 이 무시됩니다 PYTHONLEGACYWINDOWSIOENCODING
.
코드 페이지를 65001로 변경하도록 제안하는 다른 그럴듯한 답변에도 불구하고 작동하지 않습니다 . (또한, 사용 인코딩 기본값을 변경하는 sys.setdefaultencoding
것입니다 좋은 아이디어 없습니다 .)
작동하는 세부 사항 및 코드는 이 질문 을 참조하십시오 .
나쁜 캐릭터를 안정적으로 표현하는 데 관심이 없다면 다음과 같이 사용할 수 있습니다 (python> = 2.6, 3.x 포함).
from __future__ import print_function
import sys
def safeprint(s):
try:
print(s)
except UnicodeEncodeError:
if sys.version_info >= (3,):
print(s.encode('utf8').decode(sys.stdout.encoding))
else:
print(s.encode('utf8'))
safeprint(u"\N{EM DASH}")
문자열의 잘못된 문자는 Windows 콘솔에서 인쇄 할 수있는 표현으로 변환됩니다.
The below code will make Python output to console as UTF-8 even on Windows.
The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redirect the output to a file.
Below code was tested with Python 2.6 on Windows.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import codecs, sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
if sys.platform == 'win32':
try:
import win32console
except:
print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n"
exit(-1)
# win32console implementation of SetConsoleCP does not return a value
# CP_UTF8 = 65001
win32console.SetConsoleCP(65001)
if (win32console.GetConsoleCP() != 65001):
raise Exception ("Cannot set console codepage to 65001 (UTF-8)")
win32console.SetConsoleOutputCP(65001)
if (win32console.GetConsoleOutputCP() != 65001):
raise Exception ("Cannot set console output codepage to 65001 (UTF-8)")
#import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
print "This is an Е乂αmp١ȅ testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\n"
Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,
For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).
def pr(s):
try:
print(s)
except UnicodeEncodeError:
for c in s:
try:
print( c, end='')
except UnicodeEncodeError:
print( '?', end='')
NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!
Just enter this code in command line before executing python script:
chcp 65001 & set PYTHONIOENCODING=utf-8
For Python 2 try:
print unicode(string, 'unicode-escape')
For Python 3 try:
import os
string = "002 Could've Would've Should've"
os.system('echo ' + string)
Or try win-unicode-console:
pip install win-unicode-console
py -mrun your_script.py
TL;DR:
print(yourstring.encode('ascii','replace'));
I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)
I wanted to parse chat messages in order to respond...
msg = s.recv(1024).decode("utf-8")
but also print them safely to the console in a human-readable format:
print(msg.encode('ascii','replace'));
This corrected the issue of the bot throwing UnicodeEncodeError: 'charmap'
errors and replaced the unicode characters with ?
.
The cause of your problem is NOT the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:
import sys
sys.getdefaultencoding()
if it says ascii, there's your cause ;-) You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:
import sys
sys.setdefaultencoding('utf-8')
and perhaps you might want to specify the encoding in your files as well:
# -*- coding: UTF-8 -*-
import sys,time
Edit: more info can be found in excellent the Dive into Python book
Kind of related on the answer by J. F. Sebastian, but more direct.
If you are having this problem when printing to the console/terminal, then do this:
>set PYTHONIOENCODING=UTF-8
Python 3.6 windows7: There is several way to launch a python you could use the python console (which has a python logo on it) or the windows console (it's written cmd.exe on it).
I could not print utf8 characters in the windows console. Printing utf-8 characters throw me this error:
OSError: [winError 87] The paraneter is incorrect
Exception ignored in: (_io-TextIOwrapper name='(stdout)' mode='w' ' encoding='utf8')
OSError: [WinError 87] The parameter is incorrect
After trying and failing to understand the answer above I discovered it was only a setting problem. Right click on the top of the cmd console windows, on the tab font
chose lucida console.
James Sulak asked,
Is there any way I can make Python automatically print a ? instead of failing in this situation?
Other solutions recommend we attempt to modify the Windows environment or replace Python's print()
function. The answer below comes closer to fulfilling Sulak's request.
Under Windows 7, Python 3.5 can be made to print Unicode without throwing a UnicodeEncodeError
as follows:
In place of: print(text)
substitute: print(str(text).encode('utf-8'))
Instead of throwing an exception, Python now displays unprintable Unicode characters as \xNN hex codes, e.g.:
Halmalo n\xe2\x80\x99\xc3\xa9tait plus qu\xe2\x80\x99un point noir
Instead of
Halmalo n’était plus qu’un point noir
Granted, the latter is preferable ceteris paribus, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.
Note: The str()
call above is needed because otherwise encode()
causes Python to reject a Unicode character as a tuple of numbers.
참고URL : https://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console
'Programming' 카테고리의 다른 글
Mercurial에서 닫힌 지점을 다시 열 수 있습니까? (0) | 2020.07.06 |
---|---|
얕은 자식 서브 모듈을 만드는 방법? (0) | 2020.07.06 |
Chrome 개발 도구 : 자바 스크립트의 [VM] 파일 (0) | 2020.07.06 |
mac OS X에서 strace -feopen <command>와 동일 (0) | 2020.07.06 |
"소수"가 유효한 속성 매개 변수 유형이 아닌 이유는 무엇입니까? (0) | 2020.07.06 |