简体   繁体   中英

python 'ascii' codec can't encode characters

I am very new to python. I am trying to send messages to android CCS server using a python script. I get the messages from RabbitMQ and then send it to CCS through XMPP. My code is based on the example code from android website. It looks like the below:

client = xmpp.Client('gcm.googleapis.com', debug=['socket'])
client.connect(server=(SERVER,PORT), secure=1, use_srv=False)
auth = client.auth(USERNAME, PASSWORD)
if not auth:
  print 'Authentication failed!'
  sys.exit(1)

client.RegisterHandler('message', message_callback)

# RabbitMQ Start ....

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

print ' [*] Waiting for messages. To exit press CTRL+C'

def callback(ch, method, properties, body):
    global client
    body = body.replace("\\","")
    try:
        send_queue.append(body)
        client.Process(1)
        flush_queued_messages()
    except Exception as ex:
        print ex


channel.basic_consume(callback,
                      queue=GCMQUEUE,
                      no_ack=True)

channel.start_consuming()

It works pretty good. But my problem is when I have emojis in my queue I get it in hex format like 22\\xe2\\x91\\xa223 and it occurs the following error:

python 'ascii' codec can't encode characters in position 366-367: ordinal not in range

I tried replacing the line :

send_queue.append(body)

To

 send_queue.append(body.encode('ascii','ignore'))

This way I can ignore the error, but this removes all the unicode characters. How to fix this ?

You should ensure the input value of body to be string, if not use str(body) then encode it as mentioned in the comments, str(body).encode('utf-8')

If it's a string already just do body.encode('utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM