问题描述
我尝试为以下问题找到解决方案,但找不到任何好的解决方案。 我有一个包含子文件夹和文件的文件夹。 某些文件可能正在被另一个进程使用(另一个进程正在将数据写入数据(.mdf 文件))。
我只想检查文件是否在使用中。
结构:
A_Folder
Setup
Data1
.mdf-file1
.mdf-file2
Data2
Data3
Evaluation
类似:
def file_in_use():
*your solution*
for file in folder:
if file_in_use(file):
print("file in use")
break
我使用的是 Win10、PyCharm 和 venv。
到目前为止我尝试过其他“解决方案”:
- psutil(有效,但速度太慢)
- open(),os.rename - 对我不起作用
- 子进程也不会工作 - 找不到我的文件名:使用 Amit 的方法 Gupta 从我下面的链接中,文件如下所示:“C:\Data\S_t_h\S-t-h\H001.mdf”
基本上我从这个问题中尝试了一切:
Check if a file is not open nor being used by another process
from subprocess import check_output,Popen,PIPE
src = r"C:\Data\S_t_h\S-t-h\H001.mdf"
files_in_use = False
def file_in_use(src):
try:
lsout = Popen(['lsof',src],stdout=PIPE,shell=False)
check_output(["grep",stdin=lsout.stdout,shell=False)
except:
return False
return True
if file_in_use(src):
files_in_use = True
我得到: FileNotFoundError: [WinError 2] 系统找不到指定的文件
此链接建议设置
winerror-2-the-system-cannot-find-the-file-specified-python
shell=True
我现在无法找到“lsof”和“grep”或者是错误的。
这里的 psutil 方法对我有用,但速度太慢(约 10 秒)
import psutil
src = r"C:\Data\S_t_h\S-t-h\H001.mdf"
def has_handle(src):
for proc in psutil.process_iter():
try:
for item in proc.open_files():
if src == item.path:
return True
except Exception:
pass
return False
print(has_handle(src))
我的解决方案:
抱歉回复晚了。 它只是与:
try:
os.rename(src,src)
return False
except OSError: # file is in use
return True
我让它比我想象的更复杂。 但无论如何,感谢你们的反馈和批评。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)