我的目标是知道文件是否被其他进程锁定,即使我无权访问该文件!
所以更清楚一点,假设我使用python的内置open()和'wb'开关(用于写入)打开文件.open()将抛出IOError与errno 13(EACCES)if
我怎样才能在这里检测到案例(2)?
我的目标平台是Windows!
您可以os.access用于检查您的访问权限。如果访问权限很好,那么它必须是第二种情况。
正如之前的评论中所建议的,os.access不会返回正确的结果。
但我在网上找到了另一个有效的代码。诀窍是它尝试重命名该文件。
来自: 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15218 次 |
| 最近记录: |