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)