2
2
3
3
# The MIT License
4
4
#
5
- # Copyright (c) 2015-2016 Sebastian Ramacher
5
+ # Copyright (c) 2015-2019 Sebastian Ramacher
6
6
#
7
7
# Permission is hereby granted, free of charge, to any person obtaining a copy
8
8
# of this software and associated documentation files (the "Software"), to deal
33
33
34
34
try :
35
35
import msvcrt
36
+ import os
36
37
has_msvcrt = True
37
38
except ImportError :
38
39
has_msvcrt = False
@@ -42,7 +43,7 @@ class BaseLock(object):
42
43
"""Base class for file locking
43
44
"""
44
45
45
- def __init__ (self , fileobj ):
46
+ def __init__ (self , fileobj , mode = None , filename = None ):
46
47
self .fileobj = fileobj
47
48
self .locked = False
48
49
@@ -69,7 +70,7 @@ class UnixFileLock(BaseLock):
69
70
"""Simple file locking for Unix using fcntl
70
71
"""
71
72
72
- def __init__ (self , fileobj , mode = None ):
73
+ def __init__ (self , fileobj , mode = None , filename = None ):
73
74
super (UnixFileLock , self ).__init__ (fileobj )
74
75
75
76
if mode is None :
@@ -93,16 +94,29 @@ class WindowsFileLock(BaseLock):
93
94
"""Simple file locking for Windows using msvcrt
94
95
"""
95
96
96
- def __init__ (self , fileobj , mode = None ):
97
- super (WindowsFileLock , self ).__init__ (fileobj )
97
+ def __init__ (self , fileobj , mode = None , filename = None ):
98
+ super (WindowsFileLock , self ).__init__ (None )
99
+ self .filename = "{}.lock" .format (filename )
98
100
99
101
def acquire (self ):
100
- msvcrt .locking (self .fileobj .fileno (), msvcrt .LK_NBLCK , 1 )
102
+ # create a lock file and lock it
103
+ self .fileobj = os .open (self .filename , os .O_RDWR | os .O_CREAT | os .O_TRUNC )
104
+ msvcrt .locking (self .fileobj , msvcrt .LK_NBLCK , 1 )
105
+
101
106
self .locked = True
102
107
103
108
def release (self ):
104
109
self .locked = False
105
- msvcrt .locking (self .fileobj .fileno (), msvcrt .LK_UNLCK , 1 )
110
+
111
+ # unlock lock file and remove it
112
+ msvcrt .locking (self .fileobj , msvcrt .LK_UNLCK , 1 )
113
+ self .fileobj .close ()
114
+ self .fileobj = None
115
+
116
+ try :
117
+ os .remove (self .filename )
118
+ except OSError :
119
+ pass
106
120
107
121
108
122
if has_fcntl :
0 commit comments