Python2.7在Windows下CMD编码为65001/utf-8时print报错[Errno 0]/[Errno 2]

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

#coding:utf-8
import os
os.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-8
import os
import win_unicode_console

win_unicode_console.enable()

os.system("chcp 65001")
a = u"你好こんにちは"
print a

方法2 不使用print

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

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

#coding:utf-8
import os
import sys
os.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

根据提供的错误信息,看起来是权限问题导致安装 `pbr` 失败。具体来说,错误提示了 `/usr/lib/python2.7/site-packages/pbr` 目录的权限被拒绝。 要解决这个问题,你可以尝试以下几种方法: 1. 使用管理员权限重新运行安装命令。在命令行中加上 `sudo` 命令来提升权限,例如: ``` sudo pip install pbr ``` 这会使用管理员权限来运行安装命令,解决权限被拒绝的问题。 2. 如果你没有管理员权限,可以尝试使用 `--user` 参数来进行用户级别的安装。这样,`pbr` 将被安装在用户主目录下的 `.local` 目录中,而不是系统目录。使用以下命令进行安装: ``` pip install --user pbr ``` 这会将 `pbr` 安装到你的用户目录下,避免权限问题。 3. 如果上述方法都无效,你可以尝试创建并设置正确的文件夹权限。首先,使用以下命令创建一个目录: ``` sudo mkdir -p /usr/lib/python2.7/site-packages/pbr ``` 接下来,使用以下命令更改目录的所有者和权限: ``` sudo chown -R your_username:your_username /usr/lib/python2.7/site-packages/pbr ``` 将 `your_username` 替换为你的用户名。这将确保你有足够的权限来安装 `pbr`。 4. 此外,根据错误信息中的提示,你可以考虑升级 `pip` 到最新版本。使用以下命令升级 `pip`: ``` pip install --upgrade pip ``` 然后再尝试安装 `pbr`。 希望这些方法能够帮助你解决问题。如果还有其他问题,请随提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值