What process is using a given file?
<p>I'm having trouble with one of my scripts, where it erratically seems to have trouble writing to its own log, throwing the error "This file is being used by another process."</p>

<p>I know there are ways to handle this with try excepts, but I'd like to find out <em>why</em> this is happening rather than just papering over it. Nothing else should be accessing that file at all. So in order to confirm the source of the bug, I'd like to find out what service is using that file.</p>

<p>Is there a way in Python on Windows to check what process is using a given file?</p>

<p>You can use Microsoft's <a href="https://technet.microsoft.com/en-us/sysinternals/handle.aspx" rel="nofollow">handle.exe</a> command-line utility. For example: </p>

<pre><code>import re
import subprocess

_handle_pat = re.compile(r'(.*?)\s+pid:\s+(\d+).*[0-9a-fA-F]+:\s+(.*)')

def open_files(name):
    """return a list of (process_name, pid, filename) tuples for
       open files matching the given name."""
    lines = subprocess.check_output('handle.exe "%s"' % name).splitlines()
    results = (_handle_pat.match(line.decode('mbcs')) for line in lines)
    return [m.groups() for m in results if m]
</code></pre>

<p>Note that this has limitations regarding Unicode filenames. In Python 2 subprocess passes <code>name</code> as an ANSI string because it calls <code>CreateProcessA</code> instead of <code>CreateProcessW</code>. In Python 3 the name gets passed as Unicode. In either case, handle.exe writes its output using a lossy ANSI encoding, so the matched filename in the result tuple may contain best-fit characters and "?" replacements.</p>

python windows file