Python:如何在Windows上将非ASCII文件名传递给Popen?

时间:2012-08-30 01:47:27

标签: windows file process python-2.7

当我使用Python运行子进程时,所有内容都可以使用ASCII参数,但如果参数是unicode(cyrillic)字符串则会失败:

cmd = [ 'dir.exe', u'по-русски' ]
p = subprocess.Popen([ 'dir.exe', u'по-русски' ])

错误日志:

Traceback (most recent call last):
  File "process.py", line 48, in <module>
    cyrillic()
  File "process.py", line 45, in cyrillic
    p = subprocess.Popen(cmd, shell=True, stdin=None, stdout=None, stderr=subprocess.PIPE)
  File "C:\Python\27\Lib\subprocess.py", line 679, in __init__
    errread, errwrite)
  File "C:\Python\27\Lib\subprocess.py", line 870, in _execute_child
    args = '{} /c "{}"'.format (comspec, args)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-10: ordinal not in range(128)

我尝试了不同的可执行文件 - 7z.ex,ls.exe - popen在运行之前就失败了。

但是如果我将unicode字符串编码为特定的编码呢?

# it works because 1251 is kinda native encoding for my Windows
cmd = [ 'dir.exe', CYRILLIC_FILE_NAME.encode('windows-1251') ]

# fails because 1257 cannot be converted to 1251 without errors
cmd = [ 'dir.exe', BALTIC_FILE_NAME.encode('windows-1251') ]

# this may work but it's not a solution because...
cmd = [ 'dir.exe', BALTIC_FILE_NAME.encode('windows-1257') ]

“糟糕”的事情,我的电脑上有不同的文件名 - 波罗的海,西里尔文等等。所以它看起来没有通用的方法将非ASCII文件名传递给Windows上的Popen ?!或者可以修复吗? (最好没有肮脏的黑客。)

Windows 7,Python 2.7.3

1 个答案:

答案 0 :(得分:1)

如果使用Python 3,它将以Unicode的形式正确传递参数。假设您的子进程可以在命令行上加载unicode参数(Python 2不能),那么它应该可以工作。

例如,此脚本在Python 3下运行时将显示西里尔字符。

import subprocess
subprocess.call(["powershell", "-c", "echo", "'по-русски'"])