LoginSignup
14
15

More than 5 years have passed since last update.

Pythonで外部コマンドの存在チェック(`which`的な)

Posted at

Pythonで外部プログラムをあつかう時、実行前に外部プログラムが存在するか確認したかったので調べました。
実行時エラーチェックもできますが、その前に利用可能なことだけ確認したいような場合を想定しています。
または、プログラムのインストールされているパスを調べたいときにも使えます。

外部プログラムはsubprocess.Popenなどで実行する前提です。
Pythonのバージョンは3.5.1と2.7.11で試しました。

たぶん一番簡単な方法(Python3.3以上)

shutilモジュールのwhich関数を使います。
コマンドが実行可能であればコマンドへパスを、見つからなければNoneを返します。

import shutil

print(shutil.which('ls'))  # > '/bin/ls'
print(shutil.which('ssss'))  # > None

Python3.3未満の使用を強いられている人たちへの救済

shutil.whichはバックポートされていないのでPython 2.7では使えません。
さっさと3.5以上に移行したほうがいいと思いますが、無理な人もいると思うので、古いPythonでも使える方法を紹介します。

distutils.spawn.find_executableshutil.whichと同じことができます。
http://stackoverflow.com/questions/5226958/which-equivalent-function-in-python

import distutils.spawn

print(distutils.span.find_executabl('ls'))  # > '/bin/ls'
print(distutils.span.find_executabl('ssss'))  # > None

これは知らないと見つからないのでは・・・
3系でもこの方法は使えますが、distutilsはマイナー扱いされてドキュメントもなくなっていました。
http://docs.python.jp/3/library/distutils.html

罠ポイントは

  • shutilは単数形だけどdistutilsは複数形
  • import distutilsだけだとspawnモジュールがインポートされないのでimport distuils.spawnまたはfrom distutils import spawnする必要がある

などです。

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15