Python | shutil.which() method

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 in automating process of copying and removal of files and directories.
shutil.which() method tells the path to an executable application which would be run if the given cmd was called. This method can be used to find a file on computer which 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 and 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 used
Return Value: This method returns the path to an executable application



Example #1 :
Using shutil.which() method to get location of Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain shutil.which() method 
      
# importing os module 
import os 
  
# importing shutil module 
import shutil 
  
# cmd 
cmd = 'python'
  
# Using shutil.which() method
locate = shutil.which(cmd)
  
# Print result
print(locate)

chevron_right


Output:

/usr/bin/python

Example #2 :
Using shutil.which() method to get location of C++

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain shutil.which() method 
      
# importing os module 
import os 
  
# importing shutil module 
import shutil 
  
# cmd 
cmd = 'c++'
  
# Using shutil.which() method
locate = shutil.which(cmd)
  
# Print result
print(locate)

chevron_right


Output:

/usr/bin/c++


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.