LoginSignup
151
154

More than 5 years have passed since last update.

pythonで外部のシェルスクリプトやコマンドを実行する方法

Last updated at Posted at 2014-08-12

pythonで外部のシェルスクリプトやコマンドを実行する方法です。

今回はpythonのコードに入力されたIPアドレスが正しいかをチェックする「ip-address_check.sh 」を実行してその結果を格納して表示する動作を想定しています。

外部のシェルスクリプトを実行するとなると2パターンあるのですが返り値が違います。

  1. os.system('ls -la')
      コマンドが成功すれば0が返ってきます。

  2. commands.getoutput("ls -la")
      実際に実行した結果が返ってきます。

#!/usr/bin/env python

import commands

check = commands.getoutput("./ip-address_check.sh 192.168.1.1")

print check

ip-address_checkでは書式に問題なければOKを返すように作成されていますので、この場合print checkによりpythonの出力結果としてもOKが出力されます。

意外とコマンドを忘れがちなのでメモしておきます。



python歴半年になったので読んだ参考書を晒してみる
151
154
2

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
151
154