简介
官方API
这个模块主要是做数据串行化和串行化数据解析的,pickle是python语言的库,cPickle是C语言写的,后者的执行速度是前者的1000倍。但是cPickle对少数模块不支持。
使用这两个库的数据必须是python相关的,否则其他非python语言可能无法解析这些串行化数据。
主要接口
pickle.dump(obj, file[, protocol])
#Write a pickled representation of obj to the open file object file.
#protocol 这里默认是0, 保存的文件在一些编辑器会显示奇怪,用2可以解决这个问题,下同。
pickle.load(file)
#Read a string from the open file object file and interpret it as a pickle data stream, reconstructing and returning the original object hierarchy.
pickle.dumps(obj[, protocol])
#Return the pickled representation of the object as a string, instead of writing it to a file.
pickle.loads(string)
#Read a pickled object hierarchy from a string.
API使用举例
import pickle
# import cPickle as ...
pickle.dump("123", open("test.txt","wb")) #pickle into file
str1 = pickle.load(open("test.txt","rb")) #load from pickled file
当然在dump或者load过程中遇到错误会有异常抛出,可以查看上面的API获取异常的类型。
操作复杂对象
pickle操作复杂数据结构或者对象、函数等:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
############################
#File Name: pickle_test.py
#Author: Wang
#Mail: wang@hotmail.com
#Created Time:2017-09-23 16:56:53
############################
from pickle import *
my_dict = {'name':'wang', 'age':15}
print "initial dict: ", my_dict
ss = dumps(my_dict)
tt = loads(ss)
print "loaded dict: ", tt
def my_func(x, y):
print "the number inputted: %d,%d, sum is: "%(x,y),
return x + y
ss = dumps(my_func)
tt = loads(ss)
print "loaded function: ", tt(2,4)
import numpy as np
class My_class:
def __init__(self):
self.name = "Lee"
self.sex = "male"
self.index = np.array([1,2,3])
def set_name(self, newname):
self.name = newname
def get_sub(self, a, b):
return a - b
my_obj = My_class()
my_obj.set_name("Zhao")
print my_obj
ss = dumps(my_obj)
tt = loads(ss)
print tt
print tt.name, tt.index, tt.get_sub(12,10)
'''
Results:
initial dict: {'age': 15, 'name': 'wang'}
loaded dict: {'age': 15, 'name': 'wang'}
loaded function: the number inputted: 2,4, sum is: 6
<__main__.My_class instance at 0x7f917a3c42d8>
<__main__.My_class instance at 0x7f9162d8d290>
Zhao [1 2 3] 2
'''
从上面结果知,pickle可以处理python的函数、复杂数据和对象,但是对象存储也是把之前的对象拷贝下来,比如这里打印结果是Zhao不是初始化的Wang。
和ROS结合
这里dumps()将数据压缩成字符串格式,在rospy里面可以把这种String消息类型发出去,从而实现在ros里复杂结构、函数和对象的发布。举例:
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
from pickle import *
import numpy as np
class My_class:
def __init__(self):
self.name = "Lee"
self.sex = "male"
self.index = np.array([1,2,3])
def set_name(self, newname):
self.name = newname
def get_sub(self, a, b):
return a - b
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = dumps(My_class)
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass