python-2.7 - 带有 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)
解决方案
在 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
推荐阅读
- angular - 调用 API 后 Angular 不会重新渲染 html 组件
- c++ - 尝试/捕获 C++ 程序中的所有块不起作用
- python - 为 sort() 创建自己的密钥
- azure-active-directory - Azure Active Directory 中的角色和权限
- c# - Xamarin StartTimer 从 TimeSpan 中减去秒数不起作用
- python - 在python中获取硒数据并附加到字典{key:value}对中
- typescript - 获取类型完全列出(用于复制/粘贴)
- dll - DLL 查找在应用程序加载时失败
- mysql - SQLInvalidAuthorizationSpecException: (conn=63818) 用户 'ravi'@'hostname' 的访问被拒绝(使用密码:YES)
- r - 如何在 IVPROBIT 中使矩阵为正定?