7

What is the best method for identifying an executable within Python?

I found that the following function will find the notepad executable

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

another way to do it.

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

While both methods work for notepad, I can't seem to get them to find other executables like vlc.exe, gimp-2.10.exe, or others. What is a better method for finding executable files on a computer?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Hojo.Timberwolf
  • 985
  • 1
  • 11
  • 32
  • 1
    Have a look at this question : https://stackoverflow.com/questions/53132434/list-of-installed-programs – vcp Mar 28 '19 at 10:15
  • 3
    Both of the methods above will by default search you PATH in order to find the executables. If they are not on the the path it naturally cannot find them. What exactly are you trying to achieve? – John Sloper Mar 28 '19 at 10:16
  • This question was spurred while I was helping answer another question. After doing some searching I found these commands. – Hojo.Timberwolf Mar 28 '19 at 10:27
  • 3
    Your question seems to be very specific to Windows and finding executables which are not necessarily on the `PATH`. Perhaps [edit] to clarify the scope? – tripleee Mar 28 '19 at 10:37

2 Answers2

3

Here is platform independent efficient way to do it:

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])
Farshid Ashouri
  • 16,143
  • 7
  • 52
  • 66
  • 4
    `popen` will execute a process which is might be not desired behaviour leading to creation log files, loading dependent libraries and other things. – Andry Oct 23 '19 at 15:28
  • Now `errno` is individual python module and must independently be imported via `import errno` – MPEI_stud Aug 31 '23 at 16:41
1

Here below is the snippet which would help you to retrieve the necessary details :

Windows Management Instrumentation (WMI) is Microsoft’s implementation of Web-Based Enterprise Management (WBEM), an industry initiative to provide a Common Information Model (CIM) for pretty much any information about a computer system.

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))
redhatvicky
  • 1,912
  • 9
  • 8