首页 > 解决方案 > 带有 unicode 路径的 Python 2.7 子进程

问题描述

几天来,我一直遭受 UnicodeEncodeError 的困扰。
我搜索了一些文章,但它们都不起作用。
我试过这样

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)

我该如何解决这个问题?

我的解决方案

我被困在复杂的案件中。要运行 unicode 路径,我必须使用“ cp949 ”编码和os.realpath如下

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)

标签: python-2.7unicodesubprocess

解决方案


在 Python2.7 的情况下:

您应该定义源代码编码,将其添加到脚本的顶部:

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

它在控制台和 IDE 中工作方式不同的原因很可能是因为设置了不同的默认编码。您可以通过运行来检查它:

import sys
print sys.getdefaultencoding()

完整代码:

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

输出:

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

在 Python3 的情况下:

您应该将其编码为utf-8. 我已经尝试过了,它按预期工作。

代码:

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

输出:

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

推荐阅读