shutil.which
まだ議論されていないオプションをお勧めします: の Python 実装which、具体的にはshutil.which. Python 3.3 で導入され、Linux、Mac、および Windows をサポートするクロスプラットフォームです。whichcraftを介して Python 2.x でも利用できます。ここwhichで whichcraftのコードをそのまま切り取って、プログラムに挿入することもできます。
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
from shutil import which
return which(name) is not None
distutils.spawn.find_executable
すでに言及されている別のオプションはdistutils.spawn.find_executable.
find_executableのドキュメント文字列は次のとおりです。
「パス」にリストされたディレクトリで「実行可能ファイル」を見つけようとします
したがって、注意を払うと、関数の名前がやや誤解を招くことに気付くでしょう。とは異なりwhich、find_executableが実行可能としてマークされていることを実際に確認するのではなくexecutable、PATH 上にあることのみを確認します。find_executableしたがって、プログラムが利用可能でないときに利用可能であることを示すことは完全に可能です (ただし、可能性は低いです) 。
たとえば、/usr/bin/wget実行可能としてマークされていないファイルがあるとします。wgetシェルから実行すると、次のエラーが発生します: bash: /usr/bin/wget: Permission denied。which('wget') is not NoneFalsefind_executable('wget') is not Noneを返しますが、True を返します。おそらくどちらの関数を使用しても問題は解決しますが、これはfind_executable.
def is_tool(name):
"""Check whether `name` is on PATH."""
from distutils.spawn import find_executable
return find_executable(name) is not None