view raw
sorin sorin - 8 months ago 37
Python Question

Check if a program exists from a python script

How do I check if a program exists from a python script?

Let's say you want to check if

are available. We'll assume that they should be in path.

It would be the best to see a multiplatform solution but for the moment, Linux is enough.


  • running the command and checking for return code is not always enough as some tools do return non 0 result even when you try

  • nothing should be visible on screen when checking for the command

Also, I would appreciate a solution that that is more general, like

import subprocess
import os

def is_tool(name):
        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