python print 中文重定向失敗

2022-05-18 01:42:10 字數 1093 閱讀 3586

一直以來認為解決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 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

問題的解決

Python print中文出現錯誤

今天在學習python函式的預設引數的時候遇到一段 本想研究函式實參對函式形參中的預設引數的影響,結果遇到了print中文出現錯誤的問題,具體情況如下 usr bin env python coding utf 8 def print info name,age,city tianjin print...

python print含有中文的list

python 的 list 如果有中文的話,會印出 xe4 xb8.等等的編碼 如下所示 要如何印出中文呢?a 中文 ab print a xe4 xb8 xad xe6 x96 x87 ab 下述列出幾種作法 1.使用 decode string escape 來達成 a 中文 ab print ...

stdin,stdout,stderr和重定向

c程式自動開啟3個檔案,標準輸入,標準輸出和標準錯誤輸出。預設情況下分別指向鍵盤,顯示器,顯示器。這裡的檔案指的是指向file的指標。file是stdio.h中定義的一種派生型別。file型別指標,指向乙個關於檔案資訊的資料報,其中包括檔案i o使用的緩衝區的資訊。stdin,stdout,stde...