解决python3直接print可以但是重定向报错的问题。

比如如下代码:

#test.py
print(b'\xc2\xa0'.decode())
python test.py

没关系

python test.py > ques.txt

会报错

UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xa0’ in position 0: illegal multibyte sequence

之后尝试设置环境变量

$env:PYTHONIOENCODING="UTF-8"

解决问题了,猜测是终端直接走stdio,编码会使用utf-8,但是重定向之后会使用GBK编码的原因。从而导致某些UTF-8的字符在GBK里面无法编码。
也可以直接设置:

import sys
sys.stdout.reconfigure(encoding='utf-8')

或者使用

python -X utf8 test.py

参考python3官方文档的说法可以解释这一现象:

在这里插入图片描述

https://docs.python.org/3/library/sys.html

使用一下代码进行测试,会发现重定向的和直接打印的有很大不同:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import sys, locale, os

print("IO encodings:")
print("stdin: {}".format(sys.stdin.encoding))
print("stdout: {}".format(sys.stdout.encoding))
print("stderr: {}".format(sys.stderr.encoding))
print("\ndefault encoding: {}".format(sys.getdefaultencoding()))

print("\ntty(-like) device?")
print("stdin: {}".format(sys.stdin.isatty()))
print("stdout: {}".format(sys.stdout.isatty()))
print("stderr: {}".format(sys.stderr.isatty()))

print("\nPYTHONIOENCODING: {}".format(os.environ.get("PYTHONIOENCODING")))

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值