iTayb
iTayb

Reputation: 12763

subprocess.Popen with a unicode path

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)

returns

>>> '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?

Upvotes: 9

Views: 11087

Answers (4)

Mark Tolonen
Mark Tolonen

Reputation: 178409

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)

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)

Upvotes: 12

KurzedMetal
KurzedMetal

Reputation: 12946

>>> subprocess.call(['start', u'avión.mp3'.encode('latin1')], shell=True)
0

There's no need to call cmd if you use the shell parameter The correct way to launch an associated program is to use the cmd's start built-in AFAIK.

My 2c, HIH.

Upvotes: -1

Thanasis Petsas
Thanasis Petsas

Reputation: 4448

Your problem can be solved through smart_str function of Django module.

Use this code:

from django.utils.encoding import smart_str, smart_unicode
cmd = u'cmd /c "C:\\Pok\xe9mon.mp3"'
smart_cmd = smart_str(cmd)
subprocess.Popen(smart_cmd)

You can find information on how to install Django on Windows here. You can first install pip and then you can install Django by starting a command shell with administrator privileges and run this command:

pip install Django

This will install Django in your Python installation's site-packages directory.

Upvotes: 2

katzenversteher
katzenversteher

Reputation: 810

I think windows uses 16-bit characters, not sure if it's UCS2 or UTF16 or something like that. So I guess that it could have an issue with UTF8.

Upvotes: -2

Related Questions