最近轉換戰場,可能要很長一段時間在windows上耕耘。在python掉windows cmd命令時,發現返回的是一串亂碼,如發送dir命令,返回如下:
b' \xc7\xfd\xb6\xaf\xc6\xf7 D \xd6\xd0\xb5\xc4\xbe\xed\xc3\xbb\xd3\xd0\xb1\xea\xc7\xa9\xa1\xa3\r\n \xbe\xed\xb5\xc4\xd0\xf2\xc1\xd0\xba\xc5\xca\xc7 88E8-2AD2\r\n\r\n D:\\PyInvo \xb5\xc4\xc4\xbf\xc2\xbc\r\n\r\n2021/07/26 13:35 <DIR>
即使使用最簡單的執行echo。返回的也是一串帶b''內容
b'xxx\r\n'
那么,這個b''是什么意思呢?
從官方文檔中,我們看看
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added: Single quotes: b'still allows embedded "double" quotes' Double quotes: b"still allows embedded 'single' quotes". Triple quoted: b'''3 single quotes''', b"""3 double quotes"""
是一個bytes,序列,說明見鏈接https://docs.python.org/3/library/stdtypes.html#bytes
需要怎么處理呢?
最簡單的,如果包含文本,需要用對應的編碼方式進行解碼
如:
strvalue = bytesvalue.decode('utf-8')
參考文檔:
https://docs.python.org/3/library/stdtypes.html#bytes
https://docs.python.org/3/library/codecs.html#error-handlers
https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals