我选择使用pickle(+ base64 + TCP套接字)在我的python3代码和旧版python2代码之间通信数据,但是我在datetime对象方面遇到了麻烦:
PY3对象在PY2上的修补效果很好,但是TypeError在调用datetime构造函数时,相反会引发a ,然后UnicodeEncodeError在load_reduce函数中引发a 。
这个要点提供了简短的测试程序和日志,包括PY2和PY3泡菜的dis输出
我在PY2中使用pickle.dumps(reply, protocol=2),
然后pickle._loads(pickled, fix_imports=True, encoding='latin1')在PY3中使用
(尝试None和utf-8均未成功)
本机cPickle loads解码也失败,我仅使用纯python _loads进行调试。
这是一个datetime错误吗?也许datetime.__getstate__/__setstate__实现不兼容?
欢迎在代码上做任何评论...
PY-3.4.0泡菜:
0: \x80 PROTO 2
2: c GLOBAL 'datetime datetime'
21: q BINPUT 0
23: c GLOBAL '_codecs encode'
39: q BINPUT 1
41: X BINUNICODE u'\x07\xde\x07\x11\x0f\x06\x11\x05\n\x90'
58: q BINPUT 2
60: X BINUNICODE u'latin1'
71: q BINPUT 3
73: \x86 TUPLE2 …Run Code Online (Sandbox Code Playgroud) 我试图在Python 3中打开一个pickle文件,其代码在Python 2中有效,但现在给我一个错误.这是代码:
with open(file, 'r') as f:
d = pickle.load(f)
TypeError Traceback (most recent call last)
<ipython-input-25-38f711abef06> in <module>()
1 with open(file, 'r') as f:
----> 2 d = pickle.load(f)
TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)
我在其他SO回答中看到人们在使用open(file ,'rb')和切换到open(file ,'r')修复它时遇到了这个问题.如果这有帮助,我试着尝试open(file ,'rb')并得到以下错误:
UnpicklingError Traceback (most recent call last)
<ipython-input-26-b77842748a06> in <module>()
1 with open(file, 'rb') as f:
----> 2 d = pickle.load(f)
UnpicklingError: invalid load key, '\x0a'.
Run Code Online (Sandbox Code Playgroud)
当我打开文件f = open(file, 'r')和输入 …
我在使用 pickle 加载 pkl 文件时遇到一些问题。我使用的是 Windows 7 和 Python 3.5.1 64 位。pkl 文件是从这里下载的。
这是我的代码:
import pickle
# Load model weights and metadata
weightFile = open('vgg16.pkl', 'rb')
d = pickle.load(weightFile)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到输出
"C:\Program Files\Python35\python.exe" C:/work/lasagne/tutorial/lasagne-tutorial2.py
Traceback (most recent call last):
File "C:/work/lasagne/tutorial/lasagne-tutorial2.py", line 5, in <module>
d = pickle.load(weightFile)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xbc in position 1: ordinal not in range(128)
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
这个错误信息是什么意思?它说有一个 acsii 编解码器无法解码的字节,但是 pkl 文件不应该是二进制的(因此不包含 ascii 字符)吗?
我加载文件时做错了什么吗?我可以做什么来修复该错误?
在这里的初学者,想读入以p结尾的数据。
我的代码如下所示:
import pickle
training_file = "/home/sk/CarND-Traffic-Sign-Classifier-Project/train.p"
testing_file = "/home/sk/CarND-Traffic-Sign-Classifier-Project/test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ValueError:不支持的泡菜协议:3
有人可以指出我如何解决它,通过更改协议或以其他方式读取数据吗?