简体   繁体   中英

Python 2.7 subprocess with unicode path

I have been suffered with UnicodeEncodeError for days.
I search some articles but all of them are not working.
I tried like that

command = u'start C:\Windows\explorer.exe /select, "C:/한글.txt"'
subprocess.Popen(command, shell=True)

Traceback (most recent call last):
    subprocess.Popen(command, shell=True)
  File "C:\Python27\lib\subprocess.py", line 394, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 614, in _execute_child
    args = '{} /c "{}"'.format (comspec, args)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 43-45: ordinal not in range(128)

How can I solve the problem?

MY SOLUTION

I've been trapped in complex case. To run unicode path, I have to use " cp949 " encoding and os.realpath as below

path = os.path.realpath("C:/한글.txt")    ## realpath
command = u'start C:\Windows\explorer.exe /select, "{}"'.format(path)
command = command.encode("cp949")         ## encoding: cp949
subprocess.Popen(command, shell=True)

In case of Python2.7:

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Complete Code:

# -*- coding: utf-8 -*-
import sys
import subprocess
print(sys.getdefaultencoding())
command = u'echo "C:/한글.txt"'
subprocess.Popen(command.encode('utf-8'), shell=True)

Output:

>>> python test.py 
ascii
C:/한글.txt

In case of Python3:

You should encode it to utf-8 . I have tried it and it worked as expected.

Code:

import subprocess
command = u'echo "C:/한글.txt"'
subprocess.Popen(command.encode('utf-8'), shell=True)

Output:

>>> python3 test.py 
C:/한글.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM