如何在 Python 中找到可执行文件的位置?

How to find the location of an executable in Python?

在 Python 中识别可执行文件的最佳方法是什么?

我发现下面的函数会找到记事本可执行文件

from shutil import which
which('notepad')
Out[32]: 'C:\Windows\system32\notepad.EXE'

另一种方法。

from distutils import spawn
spawn.find_executable('notepad')
Out[38]: 'C:\Windows\system32\notepad.exe'

虽然这两种方法都适用于记事本,但我似乎无法让它们找到其他可执行文件,例如 vlc.exegimp-2。 10.exe,或其他。在计算机上查找可执行文件的更好方法是什么?

这是独立于平台的有效方法:

import subprocess
import os
import platform

def is_tool(name):
    try:
        devnull = open(os.devnull)
        subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
    except OSError as e:
        if e.errno == os.errno.ENOENT:
            return False
    return True

def find_prog(prog):
    if is_tool(prog):
        cmd = "where" if platform.system() == "Windows" else "which"
        return subprocess.call([cmd, prog])

以下是可帮助您检索必要详细信息的代码段:

Windows Management Instrumentation (WMI) 是 Microsoft 对基于 Web 的企业管理 (WBEM) 的实施,这是一项为计算机系统的几乎所有信息提供通用信息模型 (CIM) 的行业倡议。

import wmi as win_manage

w_instance = win_manage.WMI()
for details in w_instance.Win32_Product():
  print('Name=%s,Publisher=%s,Version=%s,' % (details.Caption, details.Vendor, details.Version))