如何获取子进程输出并维护编码

How to get subprocess output and maintain encoding

我很可能遗漏了一些非常简单的东西,但我无法理解为什么似乎对其他人都有效的方法对我却不起作用。

目标: 我想 运行 shell 命令以非英语字符的本机输出,捕获变量中的输出然后打印到屏幕.

问题: 我所有应该包含非英文字符的输出都被替换为?标记.

思考:是否存在编码问题?我是 运行ning python 3.8,不应该!!同样 运行ning Windows 10,但也发生在 Windows 7 和 Server 2008 中。

>>> p=subprocess.run("dir",shell=True,encoding="utf8")                     
 Volume in drive C has no label.
 Volume Serial Number is A22B-FA10

 Directory of C:\Users\jeronimo\Documents\Github

04/24/2021  08:17 AM    <DIR>          .
04/24/2021  08:17 AM    <DIR>          ..
07/21/2020  09:37 PM    <DIR>          scripts
04/24/2021  08:09 AM    <DIR>          **Администратор**
               1 File(s)            295 bytes
              11 Dir(s)  151,978,950,656 bytes free

>>> p=subprocess.run("dir",capture_output=True,shell=True,encoding="utf8")
>>> p.stdout
' Volume in drive C has no label.\n Volume Serial Number is A22B-FA10\n\n Directory of C:\Users\jeronimo\Documents\Github\n\n04/24/2021  08:17 AM    <DIR>          .\n04/24/2021  08:17 AM    <DIR>    
      ..\n05/18/2020  01:24 PM scripts\n04/24/2021  08:09 AM    <DIR>          **?????????????**\n               1 File(s)            295 bytes\n              11 Dir(s)  151,976,796,160 bytes free\n'

>>> print(p.stdout)
 Volume in drive C has no label.
 Volume Serial Number is A22B-FA10

 Directory of C:\Users\jeronimo\Documents\Github

04/24/2021  08:17 AM    <DIR>          .
04/24/2021  08:17 AM    <DIR>          ..
07/21/2020  09:37 PM    <DIR>          scripts
04/24/2021  08:09 AM    <DIR>          **?????????????**
               1 File(s)            295 bytes
              11 Dir(s)  151,976,796,160 bytes free

编辑:我试过输出到一个文件:

>>> f=open('file','a+',encoding='utf-8')                                              
>>> p=subprocess.call("dir",shell=True,encoding="utf8",stdout=f)  
>>> f.close()

Volume in drive C has no label.
Volume Serial Number is A22B-FA10
Directory of C:\Users\jeronimo\Documents\Github
04/24/2021  11:49 AM    <DIR>          .
04/24/2021  11:49 AM    <DIR>          ..
07/21/2020  09:37 PM    <DIR>          scripts
04/24/2021  08:09 AM    <DIR>          ?????????????
               1 File(s)              0 bytes
              11 Dir(s)  151,974,350,848 bytes free

我尝试了多种子流程变体 - popen、运行、check_output、call - 都给出了相同的结果。我到底做错了什么?

如果我在 运行 子进程之前更改终端编码并在子进程调用中指定 utf-8 编码已解决

os.system('chcp 65001')
output = subprocess.run(data, timeout=10, encoding="utf8", shell=True, stdin=subprocess.DEVNULL,stderr=subprocess.PIPE,stdout=subprocess.PIPE)