当我使用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') ]“坏”的事情,我的电脑上有不同的文件名-波罗的海,西里尔和更多。所以看起来没有通用的方法可以将非ASCII文件名传递给Windows上的Popen?!或者,这个问题还能解决吗?(最好不要使用肮脏的黑客。)
Windows 7,Python 2.7.3
发布于 2014-01-16 21:24:53
如果您使用Python 3,它将正确地将参数作为Unicode传递。假设您的子进程可以在命令行上加载unicode参数(Python 2不能),那么它应该可以工作。
例如,此脚本在Python 3下运行时将显示西里尔文字符。
import subprocess
subprocess.call(["powershell", "-c", "echo", "'по-русски'"])https://stackoverflow.com/questions/12188848
复制相似问题