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

时间:2019-03-28 10:08:01

标签: python path executable

在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.exe gimp-2.10.exe 或其他可执行文件。在计算机上查找可执行文件的更好方法是什么?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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))
相关问题