sorin sorin - 2 months ago 8
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

wget
or
curl
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.

Hints:


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

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



Also, I would appreciate a solution that that is more general, like
is_tool(name)

Answer
import subprocess
import os

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
Comments