这是演示泡菜基本用法的示例:
# 进口泡菜 try: import cPickle as pickle # Python 2 except ImportError: import pickle # Python 3 # 创建Pythonic对象: class Family(object): def __init__(self, names): self.sons= names def __str__(self): return ' '.join(self.sons) my_family = Family(['John', 'David']) # 转储到字符串 pickle_data = pickle.dumps(my_family, pickle.HIGHEST_PROTOCOL) # 转储到文件 with open('family.p', 'w') as pickle_file: pickle.dump(families, pickle_file, pickle.HIGHEST_PROTOCOL) # 从字符串加载 my_family = pickle.loads(pickle_data) # 从文件加载 with open('family.p', 'r') as pickle_file: my_family = pickle.load(pickle_file)
有关泡菜的详细信息,请参见泡菜。
警告:泡菜的官方文档清楚地表明,没有安全保证。不要加载任何您不信任其来源的数据。