LoginSignup
226
199

More than 5 years have passed since last update.

python上でunixコマンドを実行する

Last updated at Posted at 2016-02-15

subprocessモジュールを用いてコマンドを実行する。
(※ subprocess.run()関数について追記:2/15 23:30 )

コマンドを実行する

subprocess.call(cmd)

基本的な使い方。
引数として与えられたコマンドをただ実行する。
コマンド実行が成功したら 0 が返る。

サンプル

import subprocess
res = subprocess.call('ls')
#=> lsコマンドの結果
print res
#=> コマンドが成功していれば 0

コマンドを実行する(失敗時、CalledProcessErrorをあげる)

subprocess.check_call(cmd)

引数として与えられたコマンドを実行する。
コマンド実行が成功したら 0 が返る。
失敗時、CalledProcessError 例外をあげてくれるので、try-exceptで処理できる。

サンプル

import subprocess
try:
    res = subprocess.check_call('dummy')
except:
    print "Error."
#=> Error. 

実行できないコマンドが与えられた場合、例外処理が行える。

コマンドを実行し、その出力を取得する

subprocess.check_output(cmd)

引数として与えられたコマンドを実行する。
コマンド実行が成功したら、その出力を返す。
check_callと同様に、失敗時、CalledProcessError 例外をあげてくれるので、try-exceptで処理できる。

サンプル

import subprocess
try:
    res = subprocess.check_output('ls')
except:
    print "Error."
print res
#=> lsの実行結果 

ここまでで、簡単なコマンドを実行することが可能。
最後に、引数を伴うコマンドの実行について。

コマンドに引数を加えて実行する

subprocess.call(*args)

check_call, check_outputについても同様。
配列によって、コマンドや引数を指定する。

サンプル


import subprocess
args = ['ls', '-l', '-a']
try:
    res = subprocess.check_call(args)
except:
    print "Error."
#=> "ls -l -a" の実行結果

subprocess.run(cmd)

@MiyakoDevさんからいただいたコメントを反映 )
Python3.5より、上記3つのコマンドをひとまとめにした subprocess.run() 関数が追加された。

サンプル

import subprocess
import sys

res = subprocess.run(["ls", "-l", "-a"], stdout=subprocess.PIPE)
sys.stdout.buffer.write(res.stdout)

出力を得るサンプルコード。
出力はバイト列として返ってくる。

参考

osモジュールを使った os.system やcommandsモジュールを使った commands.getstatusoutput がありましたが、現在は推奨されていないようです。

226
199
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
226
199