jjzjj

windows - python : How to pass non-ASCII file names to Popen on Windows?

coder 2024-06-13 原文

当我用 Python 运行一个子进程时,ASCII 参数的所有 id 都很好,但如果参数是 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

最佳答案

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

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

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

关于windows - python : How to pass non-ASCII file names to Popen on Windows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188848/

有关windows - python : How to pass non-ASCII file names to Popen on Windows?的更多相关文章

随机推荐