当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....错误.我认为这是因为Windows控制台不接受仅Unicode字符.最好的方法是什么??在这种情况下,有什么方法可以让Python自动打印而不是失败?
编辑: 我正在使用Python 2.5.
注意: @ LasseV.Karlsen回答带有复选标记有点过时(从2008年开始).请谨慎使用下面的解决方案/答案/建议!!
截至今天(2016年1月6日),@ JFSebastian答案更为相关.
我刚刚向Sublime添加了Python3解释器,以下代码停止工作:
for directory in directoryList:
fileList = os.listdir(directory)
for filename in fileList:
filename = os.path.join(directory, filename)
currentFile = open(filename, 'rt')
for line in currentFile: ##Here comes the exception.
currentLine = line.split(' ')
for word in currentLine:
if word.lower() not in bigBagOfWords:
bigBagOfWords.append(word.lower())
currentFile.close()
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
File "/Users/Kuba/Desktop/DictionaryCreator.py", line 11, in <module>
for line in currentFile:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 305: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我觉得这很奇怪,因为据我所知,Python3应该支持utf-8无处不在.更重要的是,相同的代码在Python2.7上没有任何问题.我已经阅读了关于添加环境变量的内容PYTHONIOENCODING,但我尝试了它 …
重现步骤:
在 GPU 上打开新的 Colab 笔记本
!ls #works
!pip install -q turicreate
import turicreate as tc
!ls #doesn't work
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-22-16fdbe588ee8> in <module>()
----> 1 get_ipython().system('ls')
2 # !nvcc --version
2 frames
/usr/local/lib/python3.6/dist-packages/google/colab/_system_commands.py in _run_command(cmd, clear_streamed_output)
165 if locale_encoding != _ENCODING:
166 raise NotImplementedError(
--> 167 'A UTF-8 locale is required. Got {}'.format(locale_encoding))
168
169 parent_pty, child_pty = pty.openpty()
NotImplementedError: A UTF-8 locale is required. Got ANSI_X3.4-1968
Run Code Online (Sandbox Code Playgroud)
不幸的是,我对为什么会发生这种情况毫无意义。有线索吗?我还将作为 turicreate 项目中的潜在问题发布。
编辑:
它看起来确实像评论中所建议的那样覆盖了我的区域设置。在导入之前我可以这样做:
import …Run Code Online (Sandbox Code Playgroud) 我可以跨平台方式更改默认(2.7)文本编码吗?open() io.open()
所以我不需要每次都指定open(...,encoding='utf-8').
在文本模式下,如果编码未指定使用的编码是与平台相关的:
locale.getpreferredencoding(False)被称为获取当前的本地编码.
虽然文档没有指定如何设置首选编码.该功能在locale模块中,所以我需要更改区域设置?是否有任何可靠的跨平台方式来设置UTF-8语言环境?它会影响除默认文本文件编码以外的任何其他内容吗?
或者区域设置更改是危险的(可能会破坏某些东西),我应该坚持自定义包装,例如:
def uopen(*args, **kwargs):
return open(*args, encoding='UTF-8', **kwargs)
Run Code Online (Sandbox Code Playgroud) [使用Python 3.2]
如果我不提供encoding参数open,则使用打开文件locale.getpreferredencoding().因此,例如,在我的Windows机器上,无论何时使用open('abc.txt'),它都将使用解码cp1252.
我想将所有输入文件切换到utf-8.显然,我可以添加encoding = 'utf-8'到我的所有open函数调用.或者,更好的是,encoding = MY_PROJECT_DEFAULT_ENCODING常量在某个地方的全局级别定义.
但我想知道是否有一种干净的方法来避免编辑我的所有open调用,通过更改"默认"编码.是否可以通过更改区域设置来更改?或者通过更改语言环境中的参数?我试图遵循Python手册,但未能理解如何使用它.
谢谢!
我正在尝试将我的整个数据库转储到 json。当我运行时,python manage.py dumpdata > data.json我收到一个错误:
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
Run Code Online (Sandbox Code Playgroud)
这是因为我的数据库中的一个角色是特殊角色。如何正确转储数据库?
仅供参考,所有其他数据库功能都可以正常工作
python ×6
locale ×3
python-3.x ×2
default ×1
django ×1
encoding ×1
turi-create ×1
unicode ×1
utf-8 ×1