鍍金池/ 問答/Python  Office/ Python3在中文Windows系統(tǒng)中以標準輸出的方式輸出UTF-8編碼字符的

Python3在中文Windows系統(tǒng)中以標準輸出的方式輸出UTF-8編碼字符的方法?

Windows系統(tǒng)的代碼頁為

C:\Users\>chcp
活動代碼頁: 936

Python 3.6.3

> import sys, locale
> print(sys.stdout.encoding, locale.getpreferredencoding())
utf-8 cp936

hello.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, locale

if __name__ == '__main__':
    print(sys.stdout.encoding, locale.getpreferredencoding())
    print('你好,世界')
    

執(zhí)行python hello.py > hello.txt,然后打開hello.txt文件顯示文件的編碼為ANSI。

怎樣能夠讓輸出的文件編碼為UTF-8?

回答
編輯回答
逗婦乳

python 2.7: output.py

print u'你好'.encode('utf-8')

cmd 窗口內(nèi)

python output.py output.txt

這時output.txt就是utf-8各式.

2018年8月30日 12:02
編輯回答
法克魷

在CMD窗口,輸入 chcp 65001 轉(zhuǎn)換為UTF-8字符

切換回原來的字符 chcp 936

2017年6月10日 05:26
編輯回答
怣痛

重新定義stdout via: https://stackoverflow.com/a/3...

utf8_stdout = os.fdopen(sys.stdout.fileno(), mode='w', encoding='utf-8', closefd=False)
sys.stdout = utf8_stdout

或者設(shè)置好環(huán)境變量
set PYTHONIOENCODING=utf-8

2017年5月19日 03:41