Python:使用å,ä和ö通过python运行windows CMD命令

时间:2014-11-18 10:39:41

标签: python cmd subprocess

我正在尝试通过python代码运行命令echo hej värld(瑞典语为“hello world”)。

到目前为止,我已经测试过:

# -*- coding: utf-8 -*-
import subprocess
print subprocess.check_output("Echo hej värld", shell = True)

# -*- coding: utf-8 -*-
import os
os.system("Echo hej värld")

两个版本都返回hej värld

如果我只是在CMD提示符中键入命令,则使用ä。

返回正确的版本

1 个答案:

答案 0 :(得分:2)

我可以在Windows 7系统上进行一些测试。问题不在于执行命令,而只在UTF-8字符的显示上。

首先,它使用Python 3.4几乎可以正常工作:它可以毫无问题地显示ä。所以我假设您使用的是2.x版本。

在2.x版本上,几乎不可能正确显示UTF8字符串。如果你设法做得正确,驱动程序会抱怨,因为字符数不同于字节数。

您可以在此处找到更多参考资料:Windows cmd encoding change causes Python crash。特别是,引用的Python bug在2014-10-02 ......仍然有效。

那该怎么办?

Windows中唯一正确的解决方案是使用仅8位字符集。如果您使用Consolas字体,Latin1(windows cp 1252)应显示瑞典字符。 CP850通常是OEM栅格字符集(在西欧),也可以正常工作。

编辑:具体操作方法

  • for Python 2.7:

    #first define a unicode string in a portable way
    utxt = u"Echo hej v\u00e4rld"
    #convert it in ANSI (whatever the current console cp can be)
    txt = utxt.encode('cp1252')
    
    os.system('echo ' + txt)
    
  • for Python 3.x:

    #first define a unicode string in a portable way
    utxt = u"Echo hej v\u00e4rld"
    
    os.system('echo ' + txt)
    

当然,如果你有# -*- coding: utf-8 -*-行,你可以安全地写värld代替v\u00e4rld

编辑(4):

eryksun的评论是对发生的事情的正确解释。 Python 2.7使用CreateProcessA意味着它希望在Windows使用的ANSI代码页而不是OEM代码页中输入命令。因此,对于使用Windows 1252作为其ANSI代码页的系统,您必须将命令转换为cp1252

Latin1(或iso-8859-1),Latin9(iso-8859-15)和windows 1252几乎是相同的字符集......但符号是它们之间的区别!如果您想在Windows下使用,则必须使用cp1252变体