我有這個代碼:
try:
execute = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print('execute', execute)
result = execute.stdout.read() execute.stderr.read()
print('normal result', result)
result = result.decode('utf-8')
print('decoded result: ', result)
reliable_send(result)
except:
reliable_send('Something went wrong ;- (')
像 whoami 或 arp-a 這樣的一些命令作業正常,我將結果發送到我的服務器,但是當我嘗試獲取 dir 或 ipconfig 時,這行result = result.decode('utf-8')拋出例外,這是什么問題?難道我做錯了什么?
錯誤:
result = result.decode('utf-8') UnicodeDecodeError: 'utf-8' 編解碼器無法解碼位置 321 中的位元組 0xff:起始位元組無效
uj5u.com熱心網友回復:
我找到了答案。
result.decode('ISO-8859-1')
它有點作業,有時它會回傳一些奇怪的東西,但總的來說它對我來說很好。如果有人知道更好的解決方案,我很想知道。
uj5u.com熱心網友回復:
在您的示例中, subprocess.Popen 已以位元組流模式打開,因此您需要知道將這些位元組作為文本插入的編碼。
如果encoding或errors被指定或text=True傳遞給subprocess.Popen,則檔案物件 stdin、stdout 和 stderr 以文本模式打開,具有指定的編碼和錯誤,如上面常用引數中所述。
您也可以嘗試使用PYTHONIOENCODING以獲得正確的結果。
我不時遇到檢測編碼的問題,并發現一個控制臺工具enca對它有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313395.html
