pickle数据序列化和反序列化

2024-03-23 14:28
文章标签 数据 序列化 pickle

本文主要是介绍pickle数据序列化和反序列化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

pickle

pickle 是 Python 中用于序列化和反序列化对象的标准模块。序列化是指将对象转换为字节流的过程,反序列化是指将字节流转换回对象的过程。pickle 提供了一种在 Python 对象和字节流之间相互转换的方式,可以用于将对象保存到文件或通过网络传输,并在需要时恢复原始对象。以下是 pickle 模块中常用的函数和方法:

pickle.dump(obj, file):将对象序列化并保存到文件中。

import pickle# 假设我们有一个字典对象
data = {'a': [1, 2.0, 3, 4 + 6j],'b': ('string', u'Unicode string'),'c': None}# 打开一个文件用于写入
with open('data.pickle', 'wb') as f:# 将字典对象序列化并保存到文件pickle.dump(data, f)

pickle.dumps(obj):将对象序列化并返回字节流。

import pickle# 假设我们有一个字典对象
data = {'a': [1, 2.0, 3, 4 + 6j],'b': ('string', u'Unicode string'),'c': None}strr = pickle.dumps(data)
print(strr)

pickle.load(file):从文件中读取字节流并反序列化为对象。

import pickle# 读取
with open('data.pickle', 'rb') as f:# 将字典对象序列化并保存到文件data = pickle.load(f)print(data)

pickle.loads(bytes_obj):将字节流反序列化为对象。

import pickle# 假设我们有一个字典对象
data = {'a': [1, 2.0, 3, 4 + 6j],'b': ('string', u'Unicode string'),'c': None}print(data)strr = pickle.dumps(data)
print(strr)data = pickle.loads(strr)
print(data)

请添加图片描述
使用 pickle 可以序列化大多数 Python 对象,包括基本数据类型(如整数、浮点数、字符串)、列表、字典、函数、类实例等。但是,pickle 序列化的字节流只能在同一个 Python 版本之间兼容,不同版本之间的兼容性较差。

pickle的应用总结

本地序列化的情况,应用较少。一般来说,大多数应用场景在网络中,将数据序列化后通过网络传输到远程结点,远程服务器上的服务接受到数据后进行反序列化,就可以使用了。但是,需要注意的是,远端接受端反序列化时必须有对应的数据类型,否则就会报错,尤其是自定义类,必须远程存在。目前,大多数项目都不是单机,不是单服务,需要通过网络将数据传送到其他结点上,这就需要大量的序列化,反序列化。但是python程序之间还可以使用pickle解决序列化和反序列化。如果是跨平台,跨语言,跨协议,pickle就不适合了,就需要公共协议,如XML/Json /protocol Buffer等。每种协议都有自己的负载,其所使用的场景都不一样,二进制的操作不一定适用于所有的场景。但越是底层的协议,越需要二进制传输。

优点:

简单易用:pickle 提供了简单的接口来序列化和反序列化 Python 对象,使用起来非常方便。

支持大多数 Python 对象:pickle 能够序列化绝大部分的 Python 数据类型,包括基本数据类型、容器类型、函数、类实例等。

保持对象间关系:当序列化一个包含多个对象引用的复杂对象时,pickle 能够保持对象间的关系,反序列化后的对象依然能够保持原有的结构。

可扩展性:pickle 提供了一些高级选项,允许用户自定义序列化和反序列化的行为,以满足特定需求。

缺点:

版本兼容性:pickle 生成的序列化数据依赖于 Python 版本,并且不同版本之间的兼容性较差。这意味着,使用不同版本的 Python 解释器可能会导致反序列化失败。

不适用于跨语言:pickle 生成的序列化数据是 Python 特定的,不适用于跨语言的数据交换。如果需要与其他语言交互,应选择其他序列化格式,如 JSON、XML 等。

安全性:由于 pickle 可能会执行反序列化过程中包含的代码,因此在使用不可信源序列化的数据时存在安全风险。反序列化不信任的数据可能会导致代码执行漏洞。

性能:与一些其他序列化格式相比,pickle 的性能可能不够高效。在需要高性能的场景下,可能需要选择其他序列化方式。

获取lustre文件系统OSS的brw_stats参数

import datetime
import json
import requestsdef writef(response, current_time):formatted_json = json.dumps(response.json(), indent=4)json1 = json.loads(formatted_json)results = json1["data"]["result"]volumes = ['thfs3-OST0000', 'thfs3-OST0001', 'thfs3-OST0002', 'thfs3-OST0003', 'thfs3-OST0004', 'thfs3-OST0005','thfs3-OST0006', 'thfs3-OST0007', 'thfs3-OST0008', 'thfs3-OST0009', 'thfs3-OST000a', 'thfs3-OST000b','thfs3-OST000c', 'thfs3-OST000d', 'thfs3-OST000e', 'thfs3-OST000f', 'thfs3-OST0010', 'thfs3-OST0011','thfs3-OST0012', 'thfs3-OST0013', 'thfs3-OST0014', 'thfs3-OST0015', 'thfs3-OST0016', 'thfs3-OST0017','thfs3-OST0018', 'thfs3-OST0019', 'thfs3-OST001a', 'thfs3-OST001b', 'thfs3-OST001c', 'thfs3-OST001d','thfs3-OST001e', 'thfs3-OST001f', 'thfs3-OST0020', 'thfs3-OST0021', 'thfs3-OST0022', 'thfs3-OST0023','thfs3-OST0024', 'thfs3-OST0025', 'thfs3-OST0026', 'thfs3-OST0027', 'thfs3-OST0028', 'thfs3-OST0029','thfs3-OST002a', 'thfs3-OST002b', 'thfs3-OST002c', 'thfs3-OST002d', 'thfs3-OST002e', 'thfs3-OST002f','thfs3-OST0030', 'thfs3-OST0031', 'thfs3-OST0032', 'thfs3-OST0033', 'thfs3-OST0034', 'thfs3-OST0035','thfs3-OST0036', 'thfs3-OST0037', 'thfs3-OST0038', 'thfs3-OST0039', 'thfs3-OST003a', 'thfs3-OST003b','thfs3-OST003c', 'thfs3-OST003d', 'thfs3-OST003e', 'thfs3-OST003f', 'thfs3-OST0040', 'thfs3-OST0041','thfs3-OST0042', 'thfs3-OST0043', 'thfs3-OST0044', 'thfs3-OST0045', 'thfs3-OST0046', 'thfs3-OST0047','thfs3-OST0048', 'thfs3-OST0049', 'thfs3-OST004a', 'thfs3-OST004b', 'thfs3-OST004c', 'thfs3-OST004d','thfs3-OST004e', 'thfs3-OST004f', 'thfs3-OST0050', 'thfs3-OST0051', 'thfs3-OST0052', 'thfs3-OST0053','thfs3-OST0054', 'thfs3-OST0055', 'thfs3-OST0056', 'thfs3-OST0057', 'thfs3-OST0058', 'thfs3-OST0059','thfs3-OST005a', 'thfs3-OST005b', 'thfs3-OST005c', 'thfs3-OST005d', 'thfs3-OST005e', 'thfs3-OST005f','thfs3-OST0060', 'thfs3-OST0061', 'thfs3-OST0062', 'thfs3-OST0063', 'thfs3-OST0064', 'thfs3-OST0065','thfs3-OST0066', 'thfs3-OST0067', 'thfs3-OST0068', 'thfs3-OST0069', 'thfs3-OST006a', 'thfs3-OST006b','thfs3-OST006c', 'thfs3-OST006d', 'thfs3-OST006e', 'thfs3-OST006f', 'thfs3-OST0070', 'thfs3-OST0071','thfs3-OST0072', 'thfs3-OST0073', 'thfs3-OST0074', 'thfs3-OST0075', 'thfs3-OST0076', 'thfs3-OST0077']for volume in volumes:read_time = "read I/O time (1/1000s):"write_time = "write I/O time (1/1000s):"read_disk_size = "read disk I/O size:"write_disk_size = "write disk I/O size:"read_pages_per_bulk = "read pages per bulk r/w:"write_pages_per_bulk = "write pages per bulk r/w:"read_in_flight = "read disk I/Os in flight:"write_in_flight = "write disk I/Os in flight:"read_discontiguous_pages = "read discontiguous pages:"write_discontiguous_pages = "write discontiguous pages:"for result in results:if result["metric"]["volume"] == volume and result["metric"]["mode"] == "read":if result["metric"]["name"] == "I/O time (1/1000s)" and result["metric"]["metric"] == "ios":read_time = read_time + result["value"][1] + "\t"if result["metric"]["name"] == "disk I/O size" and result["metric"]["metric"] == "ios":read_disk_size = read_disk_size + result["value"][1] + "\t"if result["metric"]["name"] == "pages per bulk r/w" and result["metric"]["metric"] == "rpcs":read_pages_per_bulk = read_pages_per_bulk + result["value"][1] + "\t"if result["metric"]["name"] == "disk I/Os in flight" and result["metric"]["metric"] == "ios":read_in_flight = read_in_flight + result["value"][1] + "\t"if result["metric"]["name"] == "discontiguous pages" and result["metric"]["metric"] == "rpcs":read_discontiguous_pages = read_discontiguous_pages + result["value"][1] + "\t"if result["metric"]["volume"] == volume and result["metric"]["mode"] == "write":if result["metric"]["name"] == "I/O time (1/1000s)" and result["metric"]["metric"] == "ios":write_time = write_time + result["value"][1] + "\t"if result["metric"]["name"] == "disk I/O size" and result["metric"]["metric"] == "ios":write_disk_size = write_disk_size + result["value"][1] + "\t"if result["metric"]["name"] == "pages per bulk r/w" and result["metric"]["metric"] == "rpcs":write_pages_per_bulk = write_pages_per_bulk + result["value"][1] + "\t"if result["metric"]["name"] == "disk I/Os in flight" and result["metric"]["metric"] == "ios":write_in_flight = write_in_flight + result["value"][1] + "\t"if result["metric"]["name"] == "discontiguous pages" and result["metric"]["metric"] == "rpcs":write_discontiguous_pages = write_discontiguous_pages + result["value"][1] + "\t"file = open("/thfs3/home/brw_stats/" + volume, "a")file.write(current_time + "\n")file.write(read_time + "\n" + read_disk_size + "\n" + read_pages_per_bulk + "\n" + read_in_flight + "\n" + read_discontiguous_pages + "\n")file.write(write_time + "\n" + write_disk_size + "\n" + write_pages_per_bulk + "\n" + write_in_flight + "\n" + write_discontiguous_pages + "\n")file.close()if __name__ == '__main__':url = "http://xxxxxxxxxx:9090/api/v1/query"params = {"query": "lustre2_ost_brw_stats","dedup": "true","partial_response": "false",}try:current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")response = requests.get(url, params=params, timeout=15)writef(response, current_time)except requests.Timeout:# 超时处理print("请求超时")except requests.RequestException as e:# 其他请求异常处理print("请求异常:", str(e))

这篇关于pickle数据序列化和反序列化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/838579

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

C#解析JSON数据全攻略指南

《C#解析JSON数据全攻略指南》这篇文章主要为大家详细介绍了使用C#解析JSON数据全攻略指南,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、为什么jsON是C#开发必修课?二、四步搞定网络JSON数据1. 获取数据 - HttpClient最佳实践2. 动态解析 - 快速

Olingo分析和实践之EDM 辅助序列化器详解(最佳实践)

《Olingo分析和实践之EDM辅助序列化器详解(最佳实践)》EDM辅助序列化器是ApacheOlingoOData框架中无需完整EDM模型的智能序列化工具,通过运行时类型推断实现灵活数据转换,适用... 目录概念与定义什么是 EDM 辅助序列化器?核心概念设计目标核心特点1. EDM 信息可选2. 智能类

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I