使用本地共享读/写存储器(文件/数据库)作为多个python脚本/进程的缓存的可移植方式

2024-05-17 13:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个模块或一个库,它能够像一个简单的python字典那样用简单的值(数字/字符串/列表/子字典)读写值

没有一套疯狂的方法或类,没有一个清晰的例子,比如: https://dogpilecache.sqlalchemy.org/en/latest/core_usage.html#example-using-dogpile-directly-for-caching

目前我发现fcache非常简单:https://fcache.readthedocs.io/en/stable/

但使用多个脚本访问的初始测试显示访问异常:

test1.py

from fcache.cache import FileCache

mycache = FileCache('1')

while True:
  mycache['test'] = '111'
  mycache.sync()
  x = mycache['test']
  if x != '111' and x != '222':
    print('=', x)

测试2.py

from fcache.cache import FileCache

mycache = FileCache('1')

while True:
  mycache['test'] = '222'
  mycache.sync()
  x = mycache['test']
  if x != '111' and x != '222':
    print('=', x)

test1.py输出:

Error opening file: C:\Users\User\AppData\Local\1\1\Cache\cache\74657374
= None

test2.py输出:

Traceback (most recent call last):
  File "test2.py", line 7, in <module>
    mycache.sync()
  File "C:\Python\x86\38\lib\site-packages\fcache\cache.py", line 183, in sync
    self._write_to_file(filename, self._buffer[ekey])
  File "C:\Python\x86\38\lib\site-packages\fcache\cache.py", line 250, in _write_to_file
    os.chmod(filename, self._mode)
OSError: [WinError 6800] The function attempted to use a name that is reserved for use by another transaction: 'C:\\Users\\User\\AppData\\Local\\1\\1\\Cache\\cache\\7465737
4'

multiprocessing.Lock无法帮助解决这个问题,因为同样的错误依赖于独占访问之外的其他内容

似乎fcache与多进程访问不兼容

我想将一组值存储在一个共享表中,其中一个标志表示一行。如果某个标志是否被提升,则必须从表中删除一行

我没有数量惊人的进程,我没有数量惊人的python对象与不同性质的存储。只有简单的值,可能是100,而不是更多

有没有一种简单、可靠、合理的方法可以访问一个或多个简单的文件,而无需为多个脚本/进程编写大量代码行


Tags: toinpytestselfcache字典进程
1条回答
网友
1楼 · 发布于 2024-05-17 13:29:30

我知道这个解决方案可能很愚蠢,但至少它很简单,并且通过了Windows上的测试:

test1.py(在Windows和Linux上用Python3.8测试)

from fcache.cache import FileCache
import time

mycache = FileCache('1')

i = 0
count = 0
y = '111'

while True:
  try:
    mycache['test'] = y
    mycache.sync()
    x = mycache['test']
    if x is None:
      print('FAILED', count, x)
    else:
      print('SUCCEED', count, x)
      i = 0
  except:
    # retry, has meaning on Windows
    i += 1
    if i % 10 == 0:
      # give to scheduler a break
      time.sleep(.02)
    continue
  count += 1

  if count % 10 == 0:
    # give to scheduler a break
    time.sleep(.02)

测试2.py

<<<The same code as above>>>

在我的机器上并行计算了大约10个脚本

相关问题 更多 >