Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if executable exists in Python?

Tags:

python

path

In Python, is there a portable and simple way to test if an executable program exists?

By simple I mean something like the which command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen & al and see if it fails (that's what I'm doing now, but imagine it's launchmissiles)

like image 698
Piotr Lesnicki Avatar asked Dec 18 '08 05:12

Piotr Lesnicki


People also ask

Where is the executable file in Python?

Python's shutil. which(cmd) function returns the path to the executable that would run if you called cmd in the command line. If there is no such executable, it returns None .


2 Answers

I know this is an ancient question, but you can use distutils.spawn.find_executable. This has been documented since python 2.4 and has existed since python 1.6.

import distutils.spawn distutils.spawn.find_executable("notepad.exe") 

Also, Python 3.3 now offers shutil.which().

like image 90
Nathan Binkert Avatar answered Sep 19 '22 13:09

Nathan Binkert


Easiest way I can think of:

def which(program):     import os     def is_exe(fpath):         return os.path.isfile(fpath) and os.access(fpath, os.X_OK)      fpath, fname = os.path.split(program)     if fpath:         if is_exe(program):             return program     else:         for path in os.environ["PATH"].split(os.pathsep):             exe_file = os.path.join(path, program)             if is_exe(exe_file):                 return exe_file      return None 

Edit: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.

Edit: Updated to use os.path.isfile() instead of os.path.exists() per comments.

Edit: path.strip('"') seems like the wrong thing to do here. Neither Windows nor POSIX appear to encourage quoted PATH items.

like image 32
Jay Avatar answered Sep 21 '22 13:09

Jay