什么进程正在使用给定的文件? [英] What process is using a given file?

查看:25
本文介绍了什么进程正在使用给定的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个脚本出现问题,它似乎无法正常写入自己的日志,并抛出错误该文件正被另一个进程使用."

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."

我知道有一些方法可以使用 try 例外来处理这个问题,但我想找出 为什么 会发生这种情况,而不是简单地掩盖它.根本没有其他东西可以访问该文件.因此,为了确认错误的来源,我想找出正在使用该文件的服务.

I know there are ways to handle this with try excepts, but I'd like to find out why 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.

有没有办法在 Windows 上的 Python 中检查正在使用给定文件的进程?

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

推荐答案

您可以使用微软的 handle.exe 命令行实用程序.例如:

You can use Microsoft's handle.exe command-line utility. For example:

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]

请注意,这对 Unicode 文件名有限制.在 Python 2 中,子进程将 name 作为 ANSI 字符串传递,因为它调用 CreateProcessA 而不是 CreateProcessW.在 Python 3 中,名称作为 Unicode 传递.在任一情况下,handle.exe 使用有损 ANSI 编码写入其输出,因此结果元组中匹配的文件名可能包含最适合的字符和?"替换.

Note that this has limitations regarding Unicode filenames. In Python 2 subprocess passes name as an ANSI string because it calls CreateProcessA instead of CreateProcessW. 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.

这篇关于什么进程正在使用给定的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆