[英]Python : Check file is locked
My goal is to know if a file is locked by another process or not, even if I don't have access to that file!我的目标是知道文件是否被另一个进程锁定,即使我无权访问该文件!
So to be more clear, let's say I'm opening the file using python's built-in open()
with 'wb'
switch (for writing).为了更清楚,假设我使用带有
'wb'
开关(用于写入)的python 内置open()
文件。 open()
will throw IOError
with errno 13 (EACCES)
if: open()
将抛出IOError
errno 13 (EACCES)
:
How can I detect case (2) here?我如何在这里检测案例(2)?
(My target platform is Windows) (我的目标平台是 Windows)
You can use os.access
for checking your access permission.您可以使用
os.access
检查您的访问权限。 If access permissions are good, then it has to be the second case.如果访问权限很好,那么它必须是第二种情况。
As suggested in earlier comments, os.access
does not return the correct result.正如之前评论中所建议的,
os.access
不会返回正确的结果。
But I found another code online that does work.但是我在网上找到了另一个有效的代码。 The trick is that it attempts to rename the file.
诀窍是它尝试重命名文件。
From: https://blogs.blumetech.com/blumetechs-tech-blog/2011/05/python-file-locking-in-windows.html来自: https : //blogs.blumetech.com/blumetechs-tech-blog/2011/05/python-file-locking-in-windows.html
def isFileLocked(filePath):
'''
Checks to see if a file is locked. Performs three checks
1. Checks if the file even exists
2. Attempts to open the file for reading. This will determine if the file has a write lock.
Write locks occur when the file is being edited or copied to, e.g. a file copy destination
3. Attempts to rename the file. If this fails the file is open by some other process for reading. The
file can be read, but not written to or deleted.
@param filePath:
'''
if not (os.path.exists(filePath)):
return False
try:
f = open(filePath, 'r')
f.close()
except IOError:
return True
lockFile = filePath + ".lckchk"
if (os.path.exists(lockFile)):
os.remove(lockFile)
try:
os.rename(filePath, lockFile)
sleep(1)
os.rename(lockFile, filePath)
return False
except WindowsError:
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.