在使用subprocess調用Windows命令時,遇到了字符串不顯示中文的問題,源碼以下:#-*-coding:utf-8-*-__author__ = '$USER'python
#-*-coding:utf-8-*- __author__ = '$USER' import subprocess p = subprocess.Popen('nslookup www.qq.com', stdout=subprocess.PIPE) p.wait() print('returncode:%d' % p.returncode) out = p.communicate() for i in out: if i is not None: s = str(i, encoding='utf-8') print(s)
輸出以下:服務器
returncode:0 File "F:/TECH/python/LearnPython100Days/subprocessSample.py", line 11, in <module> s = str(i, encoding='utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 0: invalid start byte
結果顯示,輸出變量在編碼爲UT-8時出錯。這是由於Windows命令行使用的是GBK編碼格式(可在命令行屬性中查看),而不是UTF-8,所以直接進行轉換是不行的。所以,將代碼修改成:編碼
s = str(i, encoding='GBK')
便可獲得正確輸出:命令行
returncode:0 服務器: UnKnown Address: 211.137.130.3 名稱: https.qq.com Addresses: 2402:4e00:8030:1::7d 121.51.142.21 Aliases: www.qq.com
在項目中,爲了不出現亂碼,最好將全部的輸出所有統一爲UTF-8格式。那麼,如何實現呢?code
1.使GBK將字節串編碼爲中文;blog
2.使用UTF-8將中文字符串編碼爲字節串;utf-8
3.使用UTF-8將該字節串解碼爲字符串,即獲得一串中文。字符串
相關代碼以下:源碼
for i in out: if i is not None: print('原始字節串(%s):\n%s' %(chardet.detect(i)['encoding'],i)) s = str(i, encoding='GBK') print('中文字符串:\n%s' %s) utf8_bytes = s.encode('UTF-8', 'ignore') print('轉碼後的字節串(%s):\n%s' % (chardet.detect(utf8_bytes)['encoding'], utf8_bytes)) utf8_str = utf8_bytes.decode('UTF-8') print('轉碼後的中文字符串:\n%s' %utf8_str)
輸出以下:it
returncode:0 原始字節串(ISO-8859-9): b'\xb7\xfe\xce\xf1\xc6\xf7: UnKnown\r\nAddress: 211.137.130.3\r\n\r\n\xc3\xfb\xb3\xc6: https.qq.com\r\nAddresses: 2402:4e00:8030:1::7d\r\n\t 121.51.142.21\r\nAliases: www.qq.com\r\n\r\n' 中文字符串: 服務器: UnKnown Address: 211.137.130.3 名稱: https.qq.com Addresses: 2402:4e00:8030:1::7d 121.51.142.21 Aliases: www.qq.com 轉碼後的字節串(utf-8): b'\xe6\x9c\x8d\xe5\x8a\xa1\xe5\x99\xa8: UnKnown\r\nAddress: 211.137.130.3\r\n\r\n\xe5\x90\x8d\xe7\xa7\xb0: https.qq.com\r\nAddresses: 2402:4e00:8030:1::7d\r\n\t 121.51.142.21\r\nAliases: www.qq.com\r\n\r\n' 轉碼後的中文字符串: 服務器: UnKnown Address: 211.137.130.3 名稱: https.qq.com Addresses: 2402:4e00:8030:1::7d 121.51.142.21 Aliases: www.qq.com
注意:
1.字節串轉爲GBK,再使用UTF-8轉爲字節串後,其值發生了變化;
2.使用chardet模塊可以檢測字節串的編碼類型,可是它的結果不保證準確,僅供參考。它將第一個字節串檢測成了‘ISO-8859-9’
3.在phthon3中,字符串的encode()方法可以獲得字節串,沒有decode方法;相應地,字節串bytes.decode()方法將其解碼爲字符串,沒有encode方法。這裏與python2不同。