22
33# The MIT License
44#
5- # Copyright (c) 2015-2016 Sebastian Ramacher
5+ # Copyright (c) 2015-2019 Sebastian Ramacher
66#
77# Permission is hereby granted, free of charge, to any person obtaining a copy
88# of this software and associated documentation files (the "Software"), to deal
3333
3434try :
3535 import msvcrt
36+ import os
3637 has_msvcrt = True
3738except ImportError :
3839 has_msvcrt = False
@@ -42,7 +43,7 @@ class BaseLock(object):
4243 """Base class for file locking
4344 """
4445
45- def __init__ (self , fileobj ):
46+ def __init__ (self , fileobj , mode = None , filename = None ):
4647 self .fileobj = fileobj
4748 self .locked = False
4849
@@ -69,7 +70,7 @@ class UnixFileLock(BaseLock):
6970 """Simple file locking for Unix using fcntl
7071 """
7172
72- def __init__ (self , fileobj , mode = None ):
73+ def __init__ (self , fileobj , mode = None , filename = None ):
7374 super (UnixFileLock , self ).__init__ (fileobj )
7475
7576 if mode is None :
@@ -93,16 +94,29 @@ class WindowsFileLock(BaseLock):
9394 """Simple file locking for Windows using msvcrt
9495 """
9596
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 )
98100
99101 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+
101106 self .locked = True
102107
103108 def release (self ):
104109 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
106120
107121
108122if has_fcntl :
0 commit comments