zoukankan      html  css  js  c++  java
  • python print 中文重定向失败

    一直以来认为解决python字符集编码,不一定需要通过sys.setdefaultencoding。因为既然python实现过程中,默认禁用了该操作,说明是不推荐的。
    通过不断的字符转换,也cover了一些问题。
    但今天在把python输出的中文重定向到文件作为日志输出时,遇到了问题。
    直接打屏没问题,但重定向到文件就会有问题。
    
    

    日志

    calculate for cc with result list offset 0 -> 255
    Traceback (most recent call last):
      File "hive_stats_sql_operation.py", line 325, in <module>
        print job_report(_result_file = result_file, _pre_job_key = pre_job_key)
      File "hive_stats_sql_operation.py", line 286, in job_report
        print dict_format(reduce(lambda x,y : x + y, local_result_list), ensure_ascii=False)
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128)
    

    问题复现与排查

    #!/bin/env python
    #coding:utf8
    import sys
    print sys.stdout.encoding
    
    #first
    python code.py
    #UTF-8
    #second 
    python code.py > debug ; cat debug
    # None
    

    问题的解决

    • 问题的原因也知道了,那么解决方法也就很明了了,就是让字符串正确的decode就ok了,所以有如下几种方法:

      • 在代码的开始调用reload(sys);sys.setdefaultencoding(‘utf8’)通过这种方式,我们制定了默认的encode字符集为utf8因此修正了以上错误
      • 在print u1的地方改成print u1.decode(‘utf8’).encode(‘utf8’)由我们来指定调用的字符集防止其调用默认的ascii
  • 相关阅读:
    ASP.NET MVC 几种 Filter 的执行过程源码解析
    C#中的线程二(BeginInvoke和Invoke)
    C#中的线程一(委托中的异步)
    C#比较dynamic和Dictionary性能
    C#微信公众平台开发—高级群发接口
    js 关闭浏览器
    切图神器 --- Assistor
    切图 -- cutterman
    mac上用teamviewer远程windows输入问题
    A quick introduction to HTML
  • 原文地址:https://www.cnblogs.com/suanec/p/10732536.html
Copyright © 2011-2022 走看看