zoukankan      html  css  js  c++  java
  • py2与py3防止中文乱码设置头部

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    
    """
    https://blog.csdn.net/weixin_34195364/article/details/88988634
    
    python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,
    python的处理常常会报错UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),
    python没办法处理非ascii编码的,此时需要自己设置python的默认编码,一般设置为utf8的编码格式。
    
    在程序中加入以下代码:即可将编码设置为utf8
    -- py2
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    import sys
    reload(sys)
    sys.setdefaultencoding(‘utf-8’)
    以上是python2的写法,但是在python3中这个需要已经不存在了,这么做也不会什么实际意义。
    在Python2.x中由于str和byte之间没有明显区别,经常要依赖于defaultencoding来做转换。
    在python3中有了明确的str和byte类型区别,从一种类型转换成另一种类型要显式指定encoding。
    
    但是仍然可以使用这个方法代替
    import importlib,sys
    importlib.reload(sys)
    """
    import os
    import sys
    import imp
    
    # 防止出现中文乱码,程序重启重新加载模块
    PY_VERSION = sys.version_info
    PY_V_INFO = str(PY_VERSION.major) + "." + str(PY_VERSION.minor) + "." + str(PY_VERSION.micro)
    
    if PY_VERSION < (3, 0):
        print('当前python版本号为:%s', PY_V_INFO)
        reload(sys)
        sys.setdefaultencoding('utf-8')
    else:
        import importlib
    
        importlib.reload(sys)
    
    人生苦短,我用python!
  • 相关阅读:
    Redis 之服务器集群配置
    Redis 之持久化(rdb、aof)
    Redis 之消息发布与订阅(publish、subscribe)
    Redis事物及锁的运用
    Redis 之hash集合结构及命令详解
    对Ul下的li标签执行点击事件——如何获取你所点击的标签
    .net 面试题(3)
    SQL Server 系统时间
    分布式内存对象缓存 memcached
    MVC 模板页和布局
  • 原文地址:https://www.cnblogs.com/sunxiuwen/p/14790570.html
Copyright © 2011-2022 走看看