当我使用 Python 运行子进程时,使用 ASCII 参数一切都很好,但如果参数是 unicode(西里尔文)字符串,则会失败:
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') ]
“坏”的事情是,我的电脑上有不同的文件名——波罗的海、西里尔文等等。所以看起来没有一般的方法可以在 Windows 上将非 ASCII 文件名传递给 Popen?!还是可以修复?(最好没有肮脏的黑客攻击。)
视窗 7,Python 2.7.3