python os.popen 提示 UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte illegal multibyte sequence

原有代码如下:

def run_silently(cmd: str) -> str:
    """返回系统命令的执行结果"""
    with os.popen(cmd) as fp:
        return fp.read().strip()

在ubuntu里执行,一点问题也没有,去到Windows就报错了

经试验:`print(run_silently('echo 拟好'))` 能正常运行, `print(run_silently('git log'))`则报错如下

$ python change_version.py
Traceback (most recent call last):
  File "change_version.py", line 79, in <module>
    main()
  File "change_version.py", line 61, in main
    print(run_silently('git log'))
  File "change_version.py", line 31, in run_silently
    return fp.read().strip()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x92 in position 592: illegal multibyte sequence

原因:编码问题

解决:修改代码如下

def run_silently(cmd: str) -> str:
    """返回系统命令的执行结果"""
    with os.popen(cmd) as fp:
        bf = fp._stream.buffer.read()
    try:
        return bf.decode().strip()
    except UnicodeDecodeError:
        return bf.decode('gbk').strip()

==== Updated At: 2023-08-22

由于0xab和0xa0这两个字符用gbk和utf8解码时分别报错了,所以修改成如下(同时支持Python2/Python3):

# coding:utf8
import os


def run_silently(
    cmd,  # type: str
    errors="ignore",  # type: str
):  # type: (...) -> str
    """返回系统命令的执行结果"""
    with os.popen(cmd) as fp:
        if not hasattr(fp, "_stream"):  # Compare with python2
            return fp.read().strip()
        bf = fp._stream.buffer.read().strip()
    try:
        return bf.decode("utf8", errors)
    except UnicodeDecodeError:
        return bf.decode("gbk", errors)


# 测试:
#print(run_silently("echo {}".format(b"\xa0\xab" + u"您好".encode("utf8"))))

注:decode函数的errors参数默认时strict,会严格比对字符集,一般场景下用ignore就可以了

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值