python subprocess.check_output 无法解码

python subprocess.check_output cant be decoded

我想通过 subprocess.check_output() 将树命令的输出保存到一个变量,但是每个字符集都给我一个错误或者没有正确解码输出。

Python3

Windows10

from subprocess import check_output  
from time import sleep  
tree = check_output("tree", shell=True).decode("utf-8") 
print(tree)  
sleep(200) 
----------------------------------------------------------- 
error: Traceback (most recent call last):
File "C:\Users\failo\Desktop\test.py", line 4, in <module>
tree = check_output("tree", shell=True).decode("utf-8") 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 65: invalid continuation byte –

tree 的输出使用Windows 画线字符来显示树结构。这些字符在代码页 850 中定义。但是您的代码假设 tree 的输出被编码为 UTF-8。错误消息告诉您关于编码的假设是错误的。改为这样做:

check_output("tree", shell=True).decode("cp850")

这给了我 print() 调用的输出:

Folder PATH listing
Volume serial number is 12E3-7FA7
    C:.
    ├───DLLs
    ├───Doc
    ├───include
    │   ├───cpython
    │   ├───internal
    │   └───pygame
    ... etc ...