在 Python 中管道標準輸出時設置正確的編碼

| | | | |

當對 Python 程序的輸出進行管道傳輸時,Python 解釋器會混淆編碼並將其設置為 None。這意味著這樣的程序:

# -*- coding: utf-8 -*- print u"åäö" 

正常運行時會正常工作,但會失敗:

UnicodeEncodeError: "ascii" codec can"t encode character u"xa0" in position 0: ordinal not in range(128)

在管道序列中使用時。

在管道時進行這項工作的最佳方法是什麼?我可以告訴它使用外殼/文件系統/無論是什麼編碼using?

目前我看到的建議是直接修改你的site.py,或者使用這個hack硬編碼defaultencoding:

# -*- coding: utf -8 -*- import sys reload(sys) sys.setdefaultencoding("utf-8") print u"åäö" 

有沒有更好的管道製作方法工作嗎?

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method