pythonsqlite锁定_用Python锁定文件

其他解决方案引用了许多外部代码库。如果您想自己动手的话,下面是一些跨平台解决方案的代码,该解决方案使用Linux/DOS系统上各自的文件锁定工具。try:

# Posix based file locking (Linux, Ubuntu, MacOS, etc.)

import fcntl, os def lock_file(f):

fcntl.lockf(f, fcntl.LOCK_EX)

def unlock_file(f):

fcntl.lockf(f, fcntl.LOCK_UN)except ModuleNotFoundError:

# Windows file locking

import msvcrt, os def file_size(f):

return os.path.getsize( os.path.realpath(f.name) )

def lock_file(f):

msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))

def unlock_file(f):

msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, file_size(f))# Class for ensuring that all file operations are atomic, treat

# initialization like a standard call to 'open' that happens to be atomic.

# This file opener *must* be used in a "with" block.class AtomicOpen:

# Open the file with arguments provided by user. Then acquire

# a lock on that file object (WARNING: Advisory locking).

def __init__(self, path, *args, **kwargs):

# Open the file and acquire a lock on the file before operating

self.file = open(path,*args, **kwargs)

# Lock the opened file

lock_file(self.file)

# Return the opened file object (knowing a lock has been obtained).

def __enter__(self, *args, **kwargs): return self.file # Unlock the file and close the file object.

def __exit__(self, exc_type=None, exc_value=None, traceback=None):

# Flush to make sure all buffered contents are written to file.

self.file.flush()

os.fsync(self.file.fileno())

# Release the lock on the file.

unlock_file(self.file)

self.file.close()

# Handle exceptions that may have come up during execution, by

# default any exceptions are raised to the user.

if (exc_type != None): return False

else: return True

现在,AtomicOpen可以在with块,通常在其中使用open声明。

警告:如果在Windows和Python上运行之前会崩溃出口我不知道锁的行为会是什么。

警告:这里提供的锁定是建议性的,而不是绝对的。所有潜在的竞争进程都必须使用“AtomicOpen”类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值