我在中运行我的PowerShell脚本,该脚本应该使用Popen运行另一个程序,然后将该程序的输出(实际上是Mercurial)输送到我的脚本中。当我试图在PowerShell中执行我的脚本时,我会得到一个编码错误。
我确信这是因为Python在获得Popen调用的输出时没有使用PowerShell使用的正确编码。问题是我不知道如何告诉Python使用正确的编码.
我的剧本看起来像
# -*- coding: utf-8 -*-
#... some imports
proc = Popen(["hg", "--cwd", self.path, "--encoding", "UTF-8"] + list(args), stdout=PIPE, stderr=PIPE)
#... other code
当我在Linux上运行这个脚本时,我没有任何问题。我也可以使用PowerShell运行Windows7HomePremium64位的脚本,没有问题。Windows 7中的PowerShell正在使用代码页850,也就是说,chcp
的输出是850
("ibm850")。
然而,当我使用默认具有编码cp437 (chcp
= 437
)的PowerShell在Windows 7初学者32位中运行脚本时,我从获得了以下错误(2.7.2版本):
File "D:\Path\to\myscript.py", line 55, in hg_command
proc = Popen(["hg", "--cwd", self.path, "--encoding", "UTF-8"] + list(args), stdout=PIPE, stderr=PIPE)
File "C:\Program files\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Program files\Python27\lib\subprocess.py", line 852, in _execute_child
args = list2cmdline(args)
File "C:\Program files\Python27\lib\subprocess.py", line 615, in list2cmdline
return ''.join(result)
UnicodeDecodeError: 'utf8' codec cant decode byte 0xe3 in position 0: unexpected end of data
我尝试了以下几点,但没有成功(即上述错误报告保持不变):
# -*- coding: utf-8 -*-
行。-- encoding UTF-8
选项。chcp 850
中将编码更改为PowerShell。关于我的具体细节,我的整个源代码都是可用的在BitBucket这里。hgapi.py
是给出错误的脚本。
更新:这个脚本是由这个其他脚本调用的,它设置了如下的编码
sys.setdefaultencoding("utf-8")
这一行看起来很重要,因为如果我注释掉它,我会得到一个不同的错误:
UnicodeDecoreError: 'ascii' codec cant decode byte 0xe3 in position 0: ordinal not in range(128)
发布于 2012-04-11 21:32:55
在使用from __future__ import unicode_literals
之后,我开始获得相同的错误,但代码的另一部分是:
out, err = [x.decode("utf-8") for x in proc.communicate()]
给出了错误
UnicodeDecodeError: 'utf8' codec cant decode byte 0xe3 in position 33 ....
实际上,x
是一个包含\xe3
(在cp1252中是ã
)的字节字符串。因此,我没有使用x.decode('utf-8')
,而是使用了x.decode('windows-1252')
,这没有给我带来bug。为了支持任何类型的编码,我最终使用了x.decode(sys.stdout.encoding)
。问题解决了.
这是在Python3.2.2中的Windows 7初学者计算机,但同一台计算机上的Python2.7也正常工作。
发布于 2012-04-03 11:53:21
尝试将编码更改为cp1252
。Windows中的Popen希望shell命令编码为cp1252
。这似乎是一个bug,而且在Python3.x中,它似乎也通过subprocess
模块:http://docs.python.org/library/subprocess.html修复了
import subprocess
subprocess.Popen(["hg", "--cwd", self.path, "--encoding", "UTF-8"] + list(args), stdout=PIPE, stderr=PIPE)
更新:
您的问题可以通过Django模块的smart_str函数来解决。
使用以下代码:
from django.utils.encoding import smart_str, smart_unicode
# the cmd should contain sthe string with the commsnd that you want to execute
smart_cmd = smart_str(cmd)
subprocess.Popen(smart_cmd)
您可以找到有关如何在Windows 这里上安装Django的信息。您可以首先安装pip,然后通过启动具有管理员权限的命令shell来安装Django,然后运行以下命令:
pip install Django
这将在Python安装的site-packages目录中安装Django。
https://stackoverflow.com/questions/9992381
复制相似问题