![]() |
VOOZH | about |
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps to automate the process of copying and removal of files and directories.
shutil.which() method tells the path to an executable application that would be run if the given cmd was called. This method can be used to find a file on a computer that is present on the PATH.
Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)
Parameters:
- cmd: A string representing the file.
- mode: This parameter specifies mode by which method should execute. os.F_OK tests existence of the path .
- os.X_OK Checks if path can be executed or we can say mode determines if the file exists and executable.
- path: This parameter specifies the path to be used, if no path is specified then the results of
os.environ()are usedReturn Value: This method returns the path to an executable application
Below are some examples of shutil.which() function of Shutil module by which we can check if a file is executable using os.X_OK and in Python:
shutil.which() MethodIn this example, the code employs shutil.which() to locate the full path of the 'python' executable in the system. The result is printed, showing the executable's path or None if not found.
Output:
/usr/bin/pythonshutil.which()In this example, the function is_executable() takes a file path as an argument, uses shutil.which() to get the executable path, and then checks if the path is not None and is executable using os.access() with the os.X_OK flag. If the file is executable, the function returns True; otherwise, it returns False.
Output:
python is executable.