简体   繁体   中英

How to load a Python 3 pickle in Python 2.7 *Without changing it*?

I am migrating a large piece of software from python 2.7 to python 3.7

For back-testing purposes, I need to be able to read old (2.7) pickles in new (3.7) python, and vice versa.

I can read old pickles in new python.

I want to also be able to read new pickles in old python.

I found this answer , but it is not good for me, as it requires me to change the pickle.

Is there a way to read a python 3 pickle in python 2 without changing the pickle ?

This is the best solution I could find:

Since I am able to change the new software, but not the old one, every time I create a pickle which has to be read by the old software, I do

def create_old_pickle(new_pickle):
    loaded = pickle.loads(new_pickle)
    repickled = pickle.dumps(loaded, protocol=2)
    return repickled

This creates old pickles in new python.

Thus old software API remains the same.

You may notice unicode->bytes problems, but that's something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM