Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill all processes locking a file

When I am running a Python script, I sometime get the error that:

"the process cannot access the file, because it is being used by another process"

Now I am wondering: Is there a way in python to:

  1. Detect which process is using that file ?
  2. Close this process ? (using for example os.system('taskkill /f /im PROCESS.exe) )
like image 261
henry Avatar asked Apr 08 '26 21:04

henry


1 Answers

You can try iterating over processes and kill it if you match the file needed with psutil:

import psutil


for p in psutil.process_iter():
try:
    if "filename" in str(p.open_files()):
        print(p.name())
        print("^^^^^^^^^^^^^^^^^")
        p.kill()
except:
    continue
like image 95
JahBless Avatar answered Apr 10 '26 09:04

JahBless