社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python`shelve`只读模式不工作

ITA • 6 年前 • 654 次点击  

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 年前