subprocess.Popen with a unicode path

前端 未结 4 1702
面向向阳花
面向向阳花 2020-12-10 07:01

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.P         


        
4条回答
  •  不知归路
    2020-12-10 07:33

    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)
    

提交回复
热议问题