Source code for Muscat.Helpers.IO.Which
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#
from typing import Union
import os
__FindExecutable = None
if os.name == "nt": # only nt coverage
try:
from win32api import FindExecutable
__FindExecutable = FindExecutable
except:
from Muscat.Helpers.Logger import Warning
Warning("module win32api is missing, you executable may not be found")
[docs]
def Which(program: str) -> str:
"""Check if an executable is reachable
and return the real "executable" (with the .exe or .bat )
inspiration from:
https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
Parameters
----------
program : str
the name of the program to find, in windows the user can omit the .exe or the .bat
extension
Returns
-------
str
return the string of the real executable or and empty string if the executable is not found
"""
def is_exe(fpath: str) -> bool:
"""Helper function the check if a file is exist and has the execution rights
Parameters
----------
fpath : str
absolute path to a file
Returns
-------
bool
true if exists, is a file , has executable permission
"""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath = os.path.dirname(program)
if fpath:
# we have a path so we search for the exact filename
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file): # pragma: no coverage (check the user path, not possible to test this)
return exe_file
if __FindExecutable is not None:
try:
_, executable = __FindExecutable(program)
except:
pass
else:
if os.path.isfile(executable):
return executable
return ""
[docs]
def CheckIntegrity(GUI: bool = False) -> str:
from Muscat.Helpers.IO.Which import Which
if os.name == "nt": # only nt coverage
# print(Which('explorer'))
print(Which('explorer'), 'C:\\WINDOWS\\explorer.exe')
print(Which("explorer.exe"), 'C:\\WINDOWS\\explorer.exe')
print(Which("C:\\WINDOWS\\explorer.exe"), 'C:\\WINDOWS\\explorer.exe')
assert (Which('None_Existent_executable_like_ls') == "")
else: # only posix coverage
print(Which('ls'))
assert (Which('ls') in ["/usr/bin/ls", "/bin/ls"])
assert (Which('explorer') == "")
return "OK"
if __name__ == '__main__': # pragma: no cover
print(CheckIntegrity(True))