10

如果您在 Windows 上进行自动化并且您正在重定向不同命令的输出(内部cmd.exe或外部,您会发现您的日志文件包含组合的 Unicode 和 ANSI 输出(这意味着它们是无效的并且不会在查看器/编辑器中很好地加载) )。

是否可以使 cmd.exe 与 UTF-8 一起使用?这个问题不是关于显示,而是关于 stdin/stdout/stderr 重定向和 Unicode。

我正在寻找一种解决方案,可以让您:

  • 使用 UTF-8 将内部命令的输出重定向到文件
  • 将支持 Unicode 的外部命令的输出重定向到文件,但编码为 UTF-8。

如果使用批处理文件无法获得这种一致性,是否有另一种解决此问题的方法,例如为此使用 python 脚本?在这种情况下,我想知道是否可以单独进行 Unicode 检测(使用脚本的用户不应该记住被调用的工具是否会输出 Unicode,它只会期望将输出转换为 UTF-8。

为简单起见,我们假设如果工具输出不是 Unicode,它将被视为 UTF-8(无代码页转换)。

4

2 回答 2

10

You can use chcp to change the active code page. This will be used for redirecting text as well:

chcp 65001

Keep in mind, though, that this will have no effect if cmd was started with the /u switch which forces Unicode (UTF-16 in this case) redirection output. If that switch is active then all output will be in UTF-16LE, regardless of the codepage set with chcp.

Also note that the console will be unusable for interactive output when set to Raster Fonts. I'm getting fun error messages in that case:

C:\Users\Johannes Rössel\Documents>x
Active code page: 65001

The system cannot write to the specified device.

So either use a sane setup (TrueType font for the console) or don't pull this stunt when using the console interactively and having a path that contains non-ASCII characters.

于 2010-04-25T14:37:16.207 回答
1
binmode(STDOUT, ":unix");

没有

use encoding 'utf8';

帮助过我。有了这个,我在打印警告中就有了广泛的性格。

于 2013-06-04T00:15:26.480 回答