Py学习  »  Python

python`shelve`只读模式不工作

ITA • 6 年前 • 586 次点击  

shelve 只读模式中断?文件上说 flag 参数工程见 dbm.open 所以我想如果我以读取模式打开,我就不能更改shelve对象。

页面 here 似乎还建议修改以只读方式打开的搁置对象会引发异常。但我仍然能够做到以下几点:

Python 3.7.2 (default, Dec 29 2018, 06:19:36) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import shelve
>>> with shelve.open('testdata') as shelf:
...      shelf['two'] = 2222
...      shelf['one'] = 1111
... 

接下来我会打开它 flag='r' writeback=False 只是为了确定。但我可以修改对象。

>>> with shelve.open('testdata', flag='r', writeback=False) as shelf:
...     for k, v in shelf.items():
...             print('Key: ', k, ' Value: ', v)
...     shelf['two'] = 1111
...     shelf['one'] = 2222
... 
Key:  one  Value:  1111
Key:  two  Value:  2222

只是为了确认,再次打开并打印它表明对象确实发生了变化:

>>> with shelve.open('testdata', flag='r', writeback=False) as shelf:
...     for k, v in shelf.items():
...             print('Key: ', k, ' Value: ', v)
... 
Key:  one  Value:  2222
Key:  two  Value:  1111

我错过了什么?这可能与选择/实施 dbm 在不同的系统上?在链接页上运行代码也不会导致: ERROR: cannot add item to database 正如页面所说的那样。

艾斯

更新: 链接页中的代码按预期工作,即引发和出错, 什么时候 我使用的是早期版本的python,即:

Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

以及在MacOS上:

Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

在Ubuntu18.04上有3.7.2,事情会崩溃。如果文件名扩展名为“.db”,则给出:

dbm.error: db type is dbm.gnu, but the module is not available

如果没有扩展,只读模式就不能工作。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38151
文章 [ 1 ]  |  最新文章 6 年前
ITA
Reply   •   1 楼
ITA    7 年前

我查到这是因为 ndbm , gdbm dumb 在里面 implementation . 在使用 NDBM GDBM 模块打开方式 flag='r' 按预期工作。但是,(至少在Ubuntu18.04上,有蟒蛇3.7.2)如果 哑的 正在使用,则行为如上所述,只读标志不会阻止写入。

由于某种原因,蟒蛇没有利用 python3-gdbm 安装在系统上。如前所述,将库从系统文件复制到水蟒环境 here 解决了这个问题。