henry
henry

Reputation: 975

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) )

Upvotes: 3

Views: 2972

Answers (1)

JahBless
JahBless

Reputation: 86

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

Upvotes: 6

Related Questions