博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python2.7在Windows下CMD编码为65001/utf-8时print报错[Errno 0]/[Errno 2]
阅读量:4624 次
发布时间:2019-06-09

本文共 1643 字,大约阅读时间需要 5 分钟。

使用python2.7处理unicode的字符串,环境变量已设置PYTHONIOENCODING为utf-8,cmd编码为utf-8时print unicode字符串会报错[Errno 0]或[Errno 2](python3.6环境下未出现此问题)

#coding:utf-8import osos.system("chcp 65001")a = u"你好こんにちは"print a

此时会报错,如果字符串只含ASCII字符就不会报错

 

经查这是windows实现C函数的问题

https://bugs.python.org/issue1602#msg148990

The underlying cause of Python's write exceptions with cp65001 is:The ANSI C write() function as implemented by the Windows console returns the number of _characters_ written rather than the number of _bytes_, which Python reasonably interprets as a "short write error". It then consults errno, which gives the effectively random error message seen.This can be bypassed by using os.write(sys.stdout.fileno(), utf8str), which will a) succeed and b) return a count <= len(utf8str).With os.write() and an appropriate font, the Windows console will correctly display a large number of characters.Possible workaround: clear errno before calling write, check for non-zero errno after. The vast majority of (non-Python) applications never check the return value of write, so don't encounter this problem.

解决方法

方法1 使用win_unicode_console模块

1.安装

pip install win_unicode_console

2.使用

很简单,导入后设置开启就行

#coding:utf-8import osimport win_unicode_consolewin_unicode_console.enable()os.system("chcp 65001")a = u"你好こんにちは"print a

方法2 不使用print

 根据issue的描述,可以用os.write(sys.stdout.fileno(), utf8str)的方式绕过

此时字符串不加u前缀,直接写入str类型

#coding:utf-8import osimport sysos.system("chcp 65001")a = "你好こんにちは"os.write(sys.stdout.fileno(), a)

偷懒方法

1.使用pycharm执行不会报错,推测pycharm自行修复了这个问题

2.只输出中文的话,那就不用utf8了,直接chcp 936然后输出a.encode("gbk","ignore")

转载于:https://www.cnblogs.com/LiuZhongbin888/p/10770232.html

你可能感兴趣的文章
双缓冲技术局部更新原理之派生自View
查看>>
PPAPI插件与浏览器的通信
查看>>
用 query 方法 获得xml 节点的值
查看>>
Hello,Android
查看>>
Sublime Text 3 build 3103 注册码
查看>>
删与改
查看>>
SAP 中如何寻找增强
查看>>
spi驱动无法建立spidev问题
查看>>
ANDROID开发之SQLite详解
查看>>
如何依靠代码提高网络性能
查看>>
Zookeeper要安装在奇数个节点,但是为什么?
查看>>
discuz 微社区安装记录
查看>>
[BZOJ4824][Cqoi2017]老C的键盘 树形dp+组合数
查看>>
配置的热更新
查看>>
MySQL事务的开启与提交,autocommit自动提交功能
查看>>
PriorityQueue
查看>>
CODEVS1403 新三国争霸
查看>>
iOS 环信离线推送
查看>>
WPFTookit Chart 高级进阶
查看>>
雷云Razer Synapse2.0使用测评 -第二次作业
查看>>