Python flock (Window+Linux都可用)[待測]


從網上面找來的,由於發現 Python 本身並沒有提供兩平台都可使用的文件鎖.
所以就在網上面找了找,還好,不用花太多時間就找到下面的代碼,先留用.
明天再來測試下..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/python
import os

# needs win32all to work on Windows
if os.name == 'nt':
import win32con, win32file, pywintypes
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
_ _overlapped = pywintypes.OVERLAPPED( )

def lock(file, flags):
hfile = win32file._get_osfhandle(file.fileno( ))
win32file.LockFileEx(hfile, flags, 0, 0xffff0000, _ _overlapped)

def unlock(file):
hfile = win32file._get_osfhandle(file.fileno( ))
win32file.UnlockFileEx(hfile, 0, 0xffff0000, _ _overlapped)
elif os.name == 'posix':
from fcntl import LOCK_EX, LOCK_SH, LOCK_NB

def lock(file, flags):
fcntl.flock(file.fileno( ), flags)

def unlock(file):
fcntl.flock(file.fileno( ), fcntl.LOCK_UN)
else:
raise RuntimeError("PortaLocker only defined for nt and posix platforms")
1
2
3
4
#!/usr/bin/python
import portalocker
file = open("somefile", "r+")
portalocker.lock(file, portalocker.LOCK_EX)