Os.popen 奇怪的编解码器问题

Os.popen strange codec issue

所以我尝试使用 os.popen 到 运行 cmd 命令,但问题是 most 命令中有西里尔字符,似乎有一些问题os.popen。当我使用此代码时

import os

stream = os.popen("dir")
output = stream.read()
print(output)

我得到这样的输出:

我需要得到这样的输出:

我也尝试用子进程库来做到这一点,但是使用子进程库要困难得多,而且在很长一段时间后我无法正确完成编码所以我真的想用 os 库来做到这一点,如果它是 possible.

我不知道如何让 os.popen 使用特定的编码(我认为这不可能),所以这是一个使用子进程的解决方案:

import subprocess

output = subprocess.run("dir", shell=True, encoding="cp866", stdout=subprocess.PIPE).stdout
print(output)

编辑:dir 是一个 shell 内置函数,因此您需要 shell=True,但您可以对普通命令使用列表参数。