相关疑难解决方法(0)

如何检查文件是否存在而没有例外?

如何在不使用该try语句的情况下查看文件是否存在?

python file file-exists

5290
推荐指数
41
解决办法
372万
查看次数

在Python中创建竞争条件文件夹

我有一个urllib2缓存模块,由于以下代码,它偶尔会崩溃:

if not os.path.exists(self.cache_location):
    os.mkdir(self.cache_location)
Run Code Online (Sandbox Code Playgroud)

问题是,到第二行执行时,文件夹可能存在,并将出错:

  File ".../cache.py", line 103, in __init__
    os.mkdir(self.cache_location)
OSError: [Errno 17] File exists: '/tmp/examplecachedir/'

这是因为脚本同时启动了很多次,由第三方代码我无法控制.

代码(在我尝试修复bug之前)可以在github上找到

我不能使用tempfile.mkstemp,因为它通过使用随机命名的目录(tempfile.py source here)来解决竞争条件,这会破坏缓存的目的.

我不想简单地丢弃错误,因为如果文件夹名称作为文件存在(不同的错误),则会引发相同的错误Errno 17错误,例如:

$ touch blah
$ python
>>> import os
>>> os.mkdir("blah")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 17] File exists: 'blah'
>>>

我无法使用,threading.RLock因为代码是从多个进程调用的.

所以,我尝试编写一个简单的基于文件的锁(这个版本可以在这里找到),但是这有一个问题:它创建一个级别的锁文件,所以/tmp/example.lock对于/tmp/example/,如果你/tmp/用作缓存目录,它会中断(因为它尝试制作/tmp.lock)..

简而言之,我需要缓存urllib2对光盘的响应.为此,我需要以多进程安全的方式访问已知目录(如果需要,创建它).它需要在OS X,Linux和Windows上运行.

思考?我能想到的唯一替代解决方案是使用SQLite3存储而不是文件重写缓存模块.

python caching race-condition

16
推荐指数
3
解决办法
4581
查看次数

标签 统计

python ×2

caching ×1

file ×1

file-exists ×1

race-condition ×1