Python中元组转整数遇TypeError求助(RabbitMQ发送场景)
解决方法
你的问题出在两个核心点:一是没有正确从单元素元组中提取整数,二是RabbitMQ的basic_publish要求body参数必须是字节类型,不能直接传入整数。
错误原因拆解
- 初始代码直接把元组
mapped_id传给body,触发expected a bytes-like object, tuple found错误; - 方案一虽然正确提取了整数,但直接将int类型传给
body,RabbitMQ无法处理int类型,导致object of type 'int' has no len()错误; - 方案二直接将整个元组转int,不符合
int()的参数要求,触发int() argument must be a string... not 'tuple'错误。
修正后的代码
def send_to_MQ(): credentials = pika.PlainCredentials(rabbit_username, rabbit_password) connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_server, rabbit_port, "/", credentials)) channel = connection.channel() channel.queue_declare(queue=rabbit_queue, durable=True) mapped_ids = get_mapped_ids() for mapped_id_tuple in mapped_ids: # 从单元素元组中直接提取整数(元组内元素本身就是int类型) mapped_id = mapped_id_tuple[0] # 将整数转为字符串后编码为字节,满足RabbitMQ的body类型要求 body = str(mapped_id).encode('utf-8') channel.basic_publish(exchange='', routing_key='hhh', body=body) print("Mapped ids sent to RabbitMQ") # 关闭连接避免资源泄漏 connection.close()
关键改动说明
- 提取整数:通过
mapped_id_tuple[0]直接获取元组中的唯一整数元素,无需额外调用int()转换; - 转换为字节类型:用
str(mapped_id).encode('utf-8')把整数转为字符串再编码成字节,完全符合RabbitMQ对body的类型要求; - 补充连接关闭:添加
connection.close()避免长期占用RabbitMQ连接资源。
内容的提问来源于stack exchange,提问作者user19441790
相关产品推荐
相关产品推荐

