shutil.which() not finding programs without appending file extension

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

The shutil.which() function in Python does not automatically append file extensions to program names when searching for executables. You need to provide the complete program name, including the file extension, if applicable.

If you want to search for programs without specifying the file extension, you can manually iterate through the PATH environment variable and check for the existence of each program file. Here's an example:

python
import os

def find_program(program):
paths = os.environ["PATH"].split(os.pathsep)
for path in paths:
executable = os.path.join(path, program)
if os.path.isfile(executable):
return executable
return None

# Example usage
program = "myprogram.exe"
executable = find_program(program)
if executable:
print("Found:", executable)
else:
print("Program not found")

In this example, the find_program() function iterates through each directory in the PATH environment variable and constructs the full path to the program by appending the program name. It then checks if the file exists using os.path.isfile(). If a matching program is found, the function returns the full path to the executable. If no program is found, it returns None.

You can modify this code according to your needs and adjust the search logic if necessary.