LoginSignup
37
43

More than 3 years have passed since last update.

Pythonからコマンドを実行する

Last updated at Posted at 2016-11-20

はじめに

pythonからコマンドを実行し、結果を受け取るにはどうすればよいか。

スクリプトから直接コマンドを実行できれば、スクリプト実行完了後に結果を処理するためのコマンドを実行するなどの手間も省くことができます。

subprocessモジュール

pythonからコマンドを実行する方法はいくつかありますが、今回はsubprocessモジュールを使った方法を説明します。

call

実行したいコマンドをリスト形式で渡すとプロセスが実行されます。

成功した場合、0が返ってきます。

In [1]: import subprocess
In [2]: subprocess.call(["ls", "-la"])
Out[2]: 0

shell=Trueとしておくと、以下のようにコマンドを実行できて便利です。

In [3]: subprocess.call("ls -la", shell=True)
Out[3]: 0

check_call

callで存在しないコマンドを渡した場合、command not foundというエラーが返ってくるだけですが、check_callを使うと実行にした場合CalledProcessErrorという例外を投げることができます。

check_callで実行した場合

CalledProcessErrorという例外が返ってきました。

In [5]: subprocess.check_call("lddd", shell=True)
/bin/sh: lddd: command not found
---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-5-00471ece15fa> in <module>()
----> 1 subprocess.check_call("lddd", shell=True)

/Users/SoichiroMurakami/.pyenv/versions/anaconda-2.4.0/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs)
    539         if cmd is None:
    540             cmd = popenargs[0]
--> 541         raise CalledProcessError(retcode, cmd)
    542     return 0
    543

CalledProcessError: Command 'lddd' returned non-zero exit status 127

callで実行した場合

command not foundが返ってくるだけです。

In [6]: subprocess.call("lddd", shell=True)
/bin/sh: lddd: command not found
Out[6]: 127

check_output

引数でコマンドを実行し、その出力を文字列として取得することができます。

コマンドの実行結果をスクリプト内で使いたい場合に便利です。

In [9]: cal_output =  subprocess.check_output("cal", shell=True)

In [10]: print cal_output
     11月 2016
日 月 火 水 木 金 土
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

その他の方法

subprocessモジュール以外のコマンド実行方法についての補足です。
以下の2つの方法があるようですが、現在はあまり推奨されていないようです。
- os.system(command)
- commands.getoutput(command)

37
43
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
37
43