Test if executable exists in Python (2023)

Test if executable exists in Python?

The easiest way I can think of:

def which (program):
def is_exe(fPfad):
devuelve os.path.isfile(fpath) and os.access(fpath, os.X_OK)

fpath, fname = os.path.split(Programma)
si path:
if is_exe(Programm):
for the path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join (Route, Programm)
if is_exe(exe_datei):
return exe_file

don't return any

To edit: Updated sample code to include logic for handling cases where the provided argument is already a full path to the executable, ie "what/bin/ls". This mimics the behavior of the UNIX "what" command.

To edit: Updated to use os.path.isfile() instead of os.path.exists() per comment.

To edit:ruta.strip(''')seems wrong here. Neither Windows nor POSIX seem to support quoted PATH elements.

Check if a program exists from a Python script

import thread

def is_tool(name):
devnull = open(os.devnull)
thread.Popen([name], stdout=devnull, stderr=devnull).communicate()
except OSError as e:
if e.errno == os.errno.ENOENT:
wrong return
return true

How do I test if an executable is present in the %PATH% of a Windows batch file?

para %%X de (myExecutable.exe) haz (SET FOUND=%%~$PATH:X)
if FOUND is defined...

If you need this for different extensions, just iterate over itRUTA:

set FOUND =
for %%e in (%PATHEXT%) do (
for %%X in (myExecutable%%e) do (
if not defined FOUND (
set FOUND=%%~$PATH:X

could it bewoIt also exists in legacy versions of Windows, but I don't have access to it, so I can't tell. The following also works on my machine:

wo myexecutable

and returns with a non-zero exit code if it could not be found. In a batch you also probably want to redirect the output toNULL, although.

Keep in mind

Chargenanalyse (.Bat) files and on the command line are different (because batch files%0%9), then you have to double that%there. It's not necessary on the command line, so the variables are flat%X.

Verify that the process runs on Windows using only Python's built-in modules

Without PyWin32, you'll have to do it the hard way and use Python's ctypes module. Luckily, there's already a post about it here on StackOverflow:

  • How can I find a process by name and kill it with ctypes?

You may also find this article helpful for getting a list of running processes:

(Video) How To Check If Files Exist With Python (For Absolute Beginners)

  • http://code.activestate.com/recipes/305279-getting-process-information-on-windows/

Check if a process is running or not in Windows?

You cannot trust lock files on Linux or Windows. It would just bite the bullet and go through all running programs. I don't think it's as "expensive" as you think it is. psutil is an excellent cross-platform Python module cable for listing all running programs on a system.

import psutil
"someProgram" in (p.name() for p in psutil.process_iter())

How can I tell if a file is executable in Python on Windows?

Here is the grepath.py I linked in my question:

#!/usr/bin/env python
"""Search for executable files in %PATH% that match PATTERN.

#XXX: Delete the --use-patext option

import fnmatch, itertools, os, re, sys, warnings
from optparse import OptionParser
from statistical import S_IMODE, S_ISREG, ST_MODE
Importfaden PIPE, Popen

def warn_import(*argumente):
"""Pass the '-Wd' option to the Python interpreter to see these warnings."""
warnings.warning("%r" % (Argumente), ImportWarning, stacklevel=2)

Class samefile_win:
def get_read_handle(Dateiname):
devuelve win32file.CreateFile (
Archiv win32.FILE_SHARE_READ,

def get_unique_id (hFile):
created_in, called_in, written_in,
file_hallo, file_lo,
index_hi, index_lo
) = win32file.GetFileInformationByHandle (hDatei)
return volume, index_hi, index_lo

def samefile_win(filename1, filename2):
"""If filename1 and filename2 represent the same file.

Works for subst, NTFS hardlinks, junction points.
It works unreliably for network drives.

Based on the Win32 API call GetFileInformationByHandle().
if same generic_file (filename 1, filename 2): returns true
hFile1 = samefile_win.get_read_handle (Name des Archivs1)
hFile2 = samefile_win.get_read_handle (Name von Archivo2)
are_equal = (samefile_win.get_unique_id (hFile1)
== mismoarchivo_win.get_unique_id (hFile2))
Returns are_same
except win32file.error:
don't return any

def canonical_path(ruta):
"""NOTE: may return an incorrect path for symbolically linked paths."""
return os.path.realpath(os.path.normcase(route))

def generisches_mismoarchive(route1, route2):
return canonical_path(path1) == canonical_path(path2)

Class is_executable_destructive:
def error_message (Basisname):
"'%(barename)s' is not recognized as internal or external\r\n
Command, executable, or batch file.\r\n"

in Russian:
devolve '"%(barename)s" \xad\xa5 \xef\xa2\xab\xef\xa5\xe2\xe1\xef \xa2\xad\xe3\xe2\xe0\xa5\xad\xad\xa5\xa9 \ xa8\xab\xa8 \xa2\xad\xa5\xe8\xad\xa5\xa9\r\n\xaa\xae\xac\xa0\xad\xa4\xae\xa9, \xa8\xe1\xaf\xae\xab \xad\xef\xa5\xac\xae\xa9 \xaf\xe0\xae\xa3\xe0\xa0\xac\xac\xae\xa9 \xa8\xab\xa8 \xaf\xa0\xaa\xa5\xe2\xad \xeb\xac \xe4\xa0\xa9\xab\xae\xac.\r\n' % dict(Basisname=Basisname)

(Video) Python Program to Check if a Given Key Exists in a Dictionary or Not (in English) | Python Exercise

def is_executable_win_destructive(ruta):
# Assume path <-> naked name, which is generally wrong
barename = os.ruta.splitext(os.ruta.basename(ruta))[0]
p = Popen(Basisname, stdout=PIPE, stderr=PIPE, Shell=True)
stdout, stderr = p.communicate()
devuelve p.poll() != 1 o stdout != '' o stderr != error_message(barename)

def is_executable_win(ruta):
"""Related to:

Known Bugs: Treat some "*~" files as executables, e.g. some "*.bat~" files
_, executable = FindExecutable(path)
return bool ( sameFile ( GetLongPathName ( executable ) ) ) )
except error:
return None # is not an exe or a doc with asoc.

def is_executable_posix(Pfad):
"""If the file is executable.

Based on which.py ​​from stdlib
#XXX ignore effective uid, guid?
test: st = os.stat(route)
except os.error:
don't return any

isregfile = S_ISREG(st[ST_MODE])
isexemode = (S_IMODE(st[ST_MODE]) & 0111)
returns bool (isregfile and isexemode)

Replace #XXX with ctypes?
desde win32api import FindExecutable, GetLongPathName, error
is_executable = is_executable_win
except ImportError, and:
warn_import("is_executable: Fallback to Posix variant", e)
is_executable = is_executable_posix

test: samefile = os.path.samefile
except AttributeError, e:
warn_import("samefile: Backup to samefile_win", e)
Import Win32 file
samefile = samewin_file.samewin_file
except ImportError, and:
warn_import("same file: back to generic", e)
samefile = samegeneric_file

def principal():
parser = OptionParser(use="""
%prog [options] PATTERN
%prog [options] -e PATTERN""", description=__doc__)
optar = parser.add_option
opt("-e", "--regex", metavar="MUSTER",
help="Use PATTERN as a regular expression")
opt("--ignore-case", action="store_true", default=True,
help="""[default] ignore case when --regex is present; for \
PATTERN not regex both FILENAME and PATTERN are \ first
Case sensitive unless required otherwise by the operating system \
opt("--no-ignore-case", dest="ignore_case", action="store_false")
opt("--use-pathext", action="store_true", default=True,
help="[default] whether to use the %PATHEXT% environment variable")
opt("--no-use-pathext", dest="use_pathext", action="store_false")
opt("--show-non-ejecutable", action="store_true", default=False,
help="Show non-executable files")

(options, arguments) = parser.parse_args()

si len(args) != 1 y no options.regex:
parser.error("Wrong number of arguments")
if not options.regex:
pattern = arguments[0]
the bad guy

if options.regex:
filepred = re.compile(options.regex, options.ignore_case und re.I).search
fnmatch_ = fnmatch.fnmatch si opciones.ignore_case sonst fnmatch.fnmatchcase
para file_pattern_symbol of "*?":
if file_pattern_symbol im Muster:
take a rest
else: # matches anywhere unless explicit file pattern symbols are provided
Muster = "*" + Muster + "*"
filepred = lambda fn: fnmatch_(fn, Muster)

if no options.regex and options.ignore_case:
filter_files = lambda files: fnmatch.filter(files, patterns)
filter_files = lambda files: itertools.ifilter(filepred, files)

if options.use_pathext:
pathexts = set frozen(map(str.upper,
os.environ.get('PATHEXT', '').split(os.pathsep)))

(Video) Python Basics - 28 part 1 - Check if Specific Words Exist in A File

seen = set()
para dirpath en os.environ.get('ROUTE', '').split(os.pathsep):
if os.path.isdir(dirpath): # assume no extension is required
# Visit the "every" directory only once
# does not recognize child drives, nodes, symbolic links, etc.
rp = canonical_path(Pfadadresse)
yes if verp: carry on
visto. add(rp); del rp

for filename in filter_files(os.listdir(dirpath)):
path = os.path.join(path address, filename)
isexe = is_executable(Pfad)

si isexe == Falso y is_executable == is_executable_win:
# The path is a document with an associated program
# Check if it is a script (.pl, .rb, .py, etc.)
if not isexe and options.use_patext:
ext = os.path.splitext(path)[1]
isexe = ext.upper() ein Pathext

if isex:
print path
elif options.show_non_executable:
print "not executable:", path

if __name__=="__main__":

Check if an executable file is present; run it if available; otherwise depart

You must have more than one space between your keyword and arguments in order for the bot framework to interpret your commands correctly.

When using the space-delimited format, two or more consecutive spaces are considered delimiters.

*** Test Case ***
[Documentation] Module exam
${rc}= Run rc and return dir ${PATH}\\${BINARY}
Execute keyword if ${rc} == 0 start test ELSE stop test

I have changed tooRun the commandbecause I couldn't find it in the libraries you imported into your script. Run And Return Rc seems to suit your needs better here.

To log your output to the console there is a Log To Console keyword you can use and yourStart test\Stop testKeywords should move under a*** Keywords ***Section

I hope it helps!

Related topics

Panda groups by value range

What is the recommended way of plotting: matplotlib or pylab

ISO time (ISO 8601) in Python

(Video) Python Program to check element is exists in list or not

Running Windows Shell Commands with Python

How to specify the working directory for Popen

Replace characters that don't work in Python

What does % do with strings in Python?

What is the purpose of _Str_ and _Repr_

Persisting styles with Python's Xlrd, Xlwt, and Xlutils.Copy

In Python, importing a filename starts with a number

Pandas: Weird performance drop when directly changing the name to Dropna

Pyqt display opencv video stream

Script Python for Minificar CSS

How to edit header in Pandas - Styling

How to set the current working directory

Ruby hash corresponds to a Python dict setdefault

Finding out what methods a Python object has

(Video) Hardware 3 Won’t Be Upgraded? | Tesla Time News

Add Tkinter line number to text widget


1. Python Tutorial: Unit Testing Your Code with the unittest Module
(Corey Schafer)
2. PYTHON : Checking if element exists with Python Selenium
(How to Fix Your Computer)
3. Python Selenium Verify Displayed Web Elements
(Parwiz Forogh)
4. Python Program to Check if a Given Key Exists in a Dictionary or Not - in Hindi #31
(WsCube Tech)
5. #25 Python Tutorial for Beginners | Prime Number in Python
6. They Come from a Place beyond this Physical Universe, with One Purpose in Mind
Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated: 03/15/2023

Views: 5902

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.