1. 程式人生 > >字串繼續編碼 報UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in rang

字串繼續編碼 報UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in rang

dd_/root>cat a2.py 
import commands
import MySQLdb
condition='20.2.224.26'
conn= MySQLdb.connect(
        host='127.0.0.1',
        port = 3306,
        user='root',
        passwd='1234567',
        db ='DEVOPS',
        charset="UTF8",
        )
cur = conn.cursor()
a = cur.execute("select user,password,name,ip,port from mon_activemq  where ip=%s ",[condition])
info = cur.fetchone()
print info
user=info[0].encode('utf-8')
code=info[1].encode('utf-8')
app=info[2].encode('utf-8')
ip=info[3].encode('utf-8')
port=info[4].encode('utf-8')
print user
print type(user)
print app
print type(app)
output=commands.getoutput("/home/mqm/sbin/activemq/view_activemq %s %s %s %s %s "  %(user,code,app,ip,port) )
print output
print type(output)
output=output.rstrip('||')
print output
print type(output)
arr1=[]
arr2=[]
arr3=[]
arr1=output.split('||')
print arr1
print type(arr1)
for x in arr1:
    arr2=x.split('->')
    arr3.append(arr2)
print '---------------------'
print arr3
print type(arr3)
print arr3[0]
print type(arr3[0][0])
print len(arr3[0][0])
print arr3[0][0].decode('utf-8')
print type(arr3[0][0].decode('utf-8'))
print len(arr3[0][0].decode('utf-8'))
print arr3[0][0].encode('utf-8')


<type 'str'>
13
訊息平臺B
<type 'unicode'>
5

已經是字串了 就不能再encode了  unicode 可以encode utf8




dd_/root>cat a2.py 
# !/usr/bin/env python
# -*- coding: utf-8 -*-
a='測試'
print a
print type(a)
print len(a)
print '2222222222222222'
b=a.encode('utf-8')


dd_/root>python a2.py
測試
<type 'str'>
6
2222222222222222
Traceback (most recent call last):
  File "a2.py", line 8, in <module>
    b=a.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)


字串是無法再繼續編碼成utf-8的 
dd_/root>python a2.py 
測試
<type 'str'>
6
2222222222222222
測試
<type 'unicode'>
2


dd_/root>cat a2.py 
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
a='測試'
print a
print type(a)
print len(a)
print '2222222222222222'
b=a.encode('utf-8')
print b
print type(b)
print len(b)

dd_/root>python a2.py 
測試
<type 'str'>
6
2222222222222222
測試
<type 'str'>
6