[파이썬] shutil `shutil.which()`: 실행 파일의 경로 찾기

When working with Python, you may often come across situations where you need to find the path of an executable file on your system. This can be useful when you want to run a command-line tool or check if a specific executable is available.

In Python, the shutil module provides a useful function called which() that helps you locate the path of an executable file. This function searches for the given executable name in the directories listed in the PATH environment variable.

Installation

The shutil module is part of the Python standard library, so you don’t need to install any additional packages. You can start using it right away.

Usage

To use shutil.which(), you simply need to pass the name of the executable you’re looking for as a string parameter. The function will then search for the executable in the directories listed in PATH and return the full path if found, or None if the executable couldn’t be located.

Here’s an example that demonstrates how to use shutil.which() to find the path of the python executable:

import shutil

executable_path = shutil.which('python')
if executable_path:
    print(f"Found python at: {executable_path}")
else:
    print("Python not found.")

The shutil.which() function returns the full path to the executable if found, allowing you to perform further actions, such as running the executable using subprocess module or checking its version using subprocess.check_output().

Conclusion

The shutil.which() function in Python’s shutil module provides a convenient way to locate the path of an executable file on your system. It helps simplify the process of finding and working with command-line tools or other executables in your Python projects.