002_028 Python 使用跨平台的文件锁

代码如下:

#encoding=utf-8

print '中国'

#使用跨平台文件锁

import os

if os.name == 'nt':
    import win32con,win32file,pywintypes
    LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
    LOCK_SH = 0
    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 lock(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("not supported")

打印结果如下: 由于还不会多线程,暂时无法验证

中国

你可能感兴趣的:(Python)