Python Pickle 模块

What pickle can store, why it is unsafe, and when to use JSON instead.

Intermediate
Key PointsUnpickling arbitrary data executes code — never load a pickle you did not create; use JSON for anything crossing a trust boundary.

Round Trip

pickle stores almost any Python object — custom instances, datetime, numpy arrays. That is its only advantage over JSON.

Python
import pickle
from datetime import datetime

data = {"when": datetime(2026, 10, 31), "nums": [1, 2, 3]}
blob = pickle.dumps(data)
print(len(blob) > 0, blob[:2])

back = pickle.loads(blob)
print(back["when"].year)
Output
True b'\x80\x04'
2026

Files and Protocol

Python
import pickle

with open("cache.pkl", "wb") as f:
    pickle.dump({"a": 1}, f, protocol=pickle.HIGHEST_PROTOCOL)

with open("cache.pkl", "rb") as f:
    print(pickle.load(f))
Output
{'a': 1}

Why It Is Dangerous

pickle.loads follows instructions in the byte stream to import modules and call functions — an attacker can craft a payload that runs os.system on load. It is equivalent to eval.

Use caseChoose
Local cache you wrote yourselfpickle (fast, any object)
HTTP API payloadJSON
Config fileJSON / TOML / YAML
Cross-language dataJSON / MessagePack
Untrusted inputNever pickle
Store JSON or msgpack in Redis/queues, never pickle — a writable queue becomes remote code execution.

Friends & Partners