当我使用grep时Python:UnicodeEncodeError [英] Python : UnicodeEncodeError when I use grep
问题描述
我使用一个简单的python脚本来获取我CID的预订结果:
simple.py
:
$ p $
data = {minorRev:current minorRev#,cid:xxx,apiKey:xxx, customerIpAddress:,creationDateStart:03/31/2013,}
url ='http:// someservice / services / rs /'
req = requests。 get(url,params = data)
print req
print req.text
print req.status_code
现在在命令提示符下,如果我执行 python simple.py
,它会完美运行并打印 req.text
variable
然而,当我尝试执行
python simple.py | grep pattern code>
我得到
UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xe4'在pos ition 1314:序号不在范围内(128)
你可以解决这个问题,编码所有 文件 结果: 文件 结果: I am using a simple python script to get reservation results for my CID :
Now on the command prompt if I do However when I try to do I get You can solve this problem encoding all File Result: File Result:
这篇关于当我使用grep时Python:UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! print
需要在发送到stdout之前对字符串进行编码,但是当进程在管道中时, sys.stdout.encoding
是无
,所以 print
收到 unicode
对象,然后尝试使用 ascii
编解码器对此对象进行编码 - 如果此 unicode $中包含非ASCII字符
unicode
对象
$ b wrong.py
:
#coding:utf-8
print u'llvaro'
alvaro @ ideas:/ tmp
$ python wrong.py
Álvaro
alvaro @ ideas:/ tmp
$ python wrong.py | grep a
Traceback(最近一次调用最后一次):
文件wrong.py,第3行,位于< module>
打印u'alvaro'
UnicodeEncodeError:'ascii'编解码器无法在位置0编码字符u'\xc1':序号不在范围内(128)
right.py
:
#编码:utf-8
打印u'llvaro'.encode('utf-8')
#unicode object encoded == Python 2中的`str`
alvaro @ ideas:/ tmp
$ python right.py
Álvaro
alvaro @ ideas:/ tmp
$ python right.py | grep a
Álvaro
simple.py
:data = {"minorRev":"current minorRev #","cid":"xxx","apiKey":"xxx","customerIpAddress":" ","creationDateStart":"03/31/2013","}
url = 'http://someservice/services/rs/'
req = requests.get(url,params=data)
print req
print req.text
print req.status_code
python simple.py
it runs perfectly and prints the req.text
variable
python simple.py | grep pattern
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1314: ordinal not in range(128)
print
needs to encode the string before sending to stdout but when the process is in a pipe, the value of sys.stdout.encoding
is None
, so print
receives an unicode
object and then it tries to encode this object using the ascii
codec -- if you have non-ASCII characters in this unicode
object, an exception will be raised.unicode
objects before sending it to the standard output (but you'll need to guess which codec to use). See these examples:wrong.py
:# coding: utf-8
print u'Álvaro'
alvaro@ideas:/tmp
$ python wrong.py
Álvaro
alvaro@ideas:/tmp
$ python wrong.py | grep a
Traceback (most recent call last):
File "wrong.py", line 3, in <module>
print u'Álvaro'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in position 0: ordinal not in range(128)
right.py
:# coding: utf-8
print u'Álvaro'.encode('utf-8')
# unicode object encoded == `str` in Python 2
alvaro@ideas:/tmp
$ python right.py
Álvaro
alvaro@ideas:/tmp
$ python right.py | grep a
Álvaro