subprocess.Popen使用unicode路径

iTa*_*ayb 7 python windows unicode command-line subprocess

我有一个我想打开的unicode文件名.以下代码:

cmd = u'cmd /c "C:\\Pok\xe9mon.mp3"'
cmd = cmd.encode('utf-8')
subprocess.Popen(cmd)
Run Code Online (Sandbox Code Playgroud)

回报

>>> 'C:\Pok?mon.mp3' is not recognized as an internal or external command, operable program or batch file.
Run Code Online (Sandbox Code Playgroud)

即使该文件确实存在.为什么会这样?

Mar*_*nen 12

看起来你正在使用Windows和Python 2.X. 使用os.startfile:

>>> import os
>>> os.startfile(u'Pokémon.mp3')
Run Code Online (Sandbox Code Playgroud)

非直观地,让命令shell执行相同的操作是:

>>> import subprocess
>>> import locale
>>> subprocess.Popen(u'Pokémon.mp3'.encode(locale.getpreferredencoding()),shell=True)
Run Code Online (Sandbox Code Playgroud)

在我的系统上,命令shell(cmd.exe)编码是cp437,但对于Windows程序是cp1252. Popen想要的shell命令编码为cp1252.这似乎是一个错误,它似乎也在Python 3.X中修复:

>>> import subprocess
>>> subprocess.Popen('Pokémon.mp3',shell=True)
Run Code Online (Sandbox Code Playgroud)

  • `os.startfile`有效,但`u'Pokémon.mp3'.encode(locale.getpreferredencoding())`当然会在ANSI代码页不映射"é"的任何语言环境中失败.在2.x`subprocess.Popen`中调用`CreateProcessA`,它将命令行解码为ANSI,因此它仅限于可以编码的命令.如果您需要一个无法编码为ANSI的命令行,那么您必须通过ctypes,cffi或扩展模块执行其他操作,例如调用`CreateProcessW`或CRT函数(如`_wsystem`). (2认同)