subprocess.Popen使用Unicode路径 [英] subprocess.Popen with a unicode path

查看:197
本文介绍了subprocess.Popen使用Unicode路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要打开的Unicode文件名。
以下代码:

I have a unicode filename that I would like to open. The following code:

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

返回

>>> 'C:\Pokיmon.mp3' is not recognized as an internal or external command, operable program or batch file.

即使文件确实存在。为什么会发生这种情况?

even though the file do exist. Why is this happening?

推荐答案

似乎您正在使用Windows和Python2.X。使用 os.startfile

It looks like you're using Windows and Python 2.X. Use os.startfile:

>>> import os
>>> os.startfile(u'Pokémon.mp3')

非直观地,让命令外壳执行

Non-intuitively, getting the command shell to do the same thing is:

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

在我的系统上,命令外壳程序(cmd.exe)编码为 cp437 ,但对于Windows程序为 cp1252 Popen 希望将shell命令编码为 cp1252 。这似乎是一个错误,并且似乎也已在Python 3.X中修复:

On my system, the command shell (cmd.exe) encoding is cp437, but for Windows programs is cp1252. Popen wanted shell commands encoded as cp1252. This seems like a bug, and it also seems fixed in Python 3.X:

>>> import subprocess
>>> subprocess.Popen('Pokémon.mp3',shell=True)

这篇关于subprocess.Popen使用Unicode路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆