首页 > 解决方案 > 问题酸洗函数的参数,包括使用 python pickle 模块的 datetime

问题描述

我正在使用 python3 并尝试使用 filecache 模块缓存一些函数。我遇到了一些日期时间的问题,我在以下示例中缩小了问题:

import pickle
import datetime
testDate = datetime.datetime(2015, 1, 1, 0, 0, 0)
arguments = (1, 2, testDate)
arguments_pickle = pickle.dumps(arguments, protocol=0).decode('ascii')

产生错误...文件“C:/wamp64/www/givingsense.eu/datamusee/python/datamusee/trials/testProblemPickle.py”,第5行,arguments_pickle = pickle.dumps(arguments,protocol = 0)。 decode('ascii') UnicodeDecodeError: 'ascii' codec can't decode byte 0xdf in position 54: ordinal not in range(128)

我坚持这一点。建议?帮助?先感谢您

标签: python-3.xdatetimepickle

解决方案


你打算做arguments_pickle什么?

将对象 obj 的腌制表示返回object文档状态。而且它绝不是一个有效的 ascii 字符串,所以当你调用.pickle.dumps()bytes.decode('ascii')

试试这个:

arguments_pickle = pickle.dumps(arguments, protocol=0)

编辑:

模块中存在错误filecache。它已经 5 年没有更新了。有 2 个开放的拉取请求就坐在那里。看来作者对维护这个模块不感兴趣。

您需要\lib\site-packages\filecache\__init__.py从这里更改第 119 行:

        arguments_pickle = _pickle.dumps(arguments, protocol=0).decode('ascii')

对此:

        arguments_pickle = str(_pickle.dumps(arguments))

推荐阅读