gpt4 book ai didi

Python 2.7.2 在 OSX 上搁置失败

转载 作者:行者123 更新时间:2023-11-30 23:33:17 25 4
gpt4 key购买 nike

使用 Python 2.7.2 上的 shelve 标准库,我编写了一个极其简单的测试来创建持久数据文件,然后立即打开它进行打印:

import os
import shelve

shelf_filename = str(__file__.split('.')[0] + '.dat')

#delete the shelf file if it exists already.
try:
os.remove(shelf_filename)
print "DELETED LEFTOVER SHELF FILE", shelf_filename
except OSError:
pass

#create a new shelf, write some data, and flush it to disk
shelf_handle = shelve.open(shelf_filename)
print "OPENED", shelf_filename, "WITH SHELF"
shelf_handle['foo'] = 'bar'
shelf_handle.close()
print "FLUSHED AND CLOSED THE SHELF"

#re-open the shelf we just wrote, read/print the data, and close it
shelf_handle = shelve.open(shelf_filename)
print "RE-OPENED", shelf_filename, "WITH SHELF"
print 'foo:', shelf_handle.get('foo')
shelf_handle.close()

#delete the shelf file
os.remove(shelf_filename)

但是,当该脚本尝试重新打开刚刚创建的架子时,该脚本意外失败:

DELETED LEFTOVER SHELF FILE shelve_test.dat
OPENED shelve_test.dat WITH SHELF
FLUSHED AND CLOSED THE SHELF
Traceback (most recent call last):
File "shelve_test.py", line 21, in <module>
shelf_handle = shelve.open(shelf_filename)
File ".../shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File ".../shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File ".../anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined

这是关于搁置的最基本的可能用法,所以我真的不明白我错过了什么,而且据我所知,我正在严格遵循文档。有一点搁置经验的人可以告诉我发生了什么事吗?

更新:这个脚本显然可以在某些平台上运行,而不能在其他平台上运行,这对于 Python 标准库来说确实有点令人惊讶。明确证实这不适用于:

Python 2.7.2 (default, May 15 2013, 13:46:05) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin

最佳答案

此版本的 Python shelve 使用的是已弃用的 dbm 包,可以通过指定不同的 dbm 来解决该问题,如下所示:

import anydbm
anydbm._defaultmod = __import__('dumbdbm')

如果将这两行添加到上面的脚本中,那么一切都会按预期进行。这确实需要搁置解决。

关于Python 2.7.2 在 OSX 上搁置失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18949832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com