HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Find a specific file, or find all executable files within the system path

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findfilethepathallexecutablesystemwithinfilesspecific

Problem

I wrote a function to find a specific file, or all the executable files with a given name and accessing flag, and I want to make sure it is as cross-platform as possible. Currently, I'm using the PATHEXT environment variable to get the extensions for files that the operating system considers executable.

import os

class CytherError(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)
        self.message = 'CytherError: {}'.format(repr(message))

def where(name, flags=os.F_OK):
    result = []
    extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
    if not extensions:
        raise CytherError("The 'PATHEXT' environment variable doesn't exist")

    paths = os.environ.get('PATH', '').split(os.pathsep)
    if not paths:
        raise CytherError("The 'PATH' environment variable doesn't exist")

    for path in paths:
        path = os.path.join(path, name)
        if os.access(path, flags):
            result.append(os.path.normpath(path))
        for ext in extensions:
            whole = path + ext
            if os.access(whole, flags):
                result.append(os.path.normpath(whole))
    return result


Usage:

In[-]: where('python')

Out[-]: "C:\Python35\python.exe"


Please be brutal in pointing out anything you find, except for:

  • Commenting



  • Docstrings



  • PEP 8 spacing



I will have these things covered later.

Solution

I could have just used the function which(), offered by shutil. Documented here.

Example:

>>> from shutil import which
>>> which('python')
'C:\Python35\python.exe'

Code Snippets

>>> from shutil import which
>>> which('python')
'C:\Python35\python.exe'

Context

StackExchange Code Review Q#123597, answer score: 7

Revisions (0)

No revisions yet.