更少.exe输出错误字符

2024-09-30 04:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的程序非常简单。它启动运行Windows port of the Unix utility less的子进程。你知道吗

import subprocess
subprocess.run('less.exe', input='Macarrão é uma delícia.', encoding='utf-8')

输入为:

Macarrão é uma delícia.

不过,结果是:

Macarrão é uma delícia.

对此有何解释?我注意到在运行python代码之前运行chcp 65001可以解决这个问题,但是查看related post我不确定这是最好的方法。引用公认答案:

chcp 65001 is very dangerous. Unless a program was specially designed to work around defects in the Windows’ API (or uses a C runtime library which has these workarounds), it would not work reliably. Win8 fixes ½ of these problems with cp65001, but the rest is still applicable to Win10.

我正在Windows1064位上运行Python3.7.0。你知道吗


Tags: oftheto程序iswindowsworksubprocess
1条回答
网友
1楼 · 发布于 2024-09-30 04:36:19

正如eryk所建议的,一种方法是将控制台代码页设置为UTF-8,然后运行更少.exe并将代码页设置回原来的状态。你知道吗

import subprocess
from ctypes import windll

prev_codepage = windll.kernel32.GetConsoleOutputCP()
windll.kernel32.SetConsoleOutputCP(65001)
subprocess.run("less.exe", input='Macarrão é uma delícia', encoding='utf-8')
windll.kernel32.SetConsoleOutputCP(prev_codepage)

相关问题 更多 >

    热门问题