LoginSignup
61

More than 3 years have passed since last update.

忘れた時の pythonでシェルスクリプト実行

Last updated at Posted at 2018-06-14

忘れた時のpythonでシェルスクリプトを実行

よく自分が忘れるので、自分が使うようのメモとして書いてます。
環境:python2.7 or python3.x

python2.7によるシェルスクリプト実行

1,「os」ライブラリ(非推奨の手法)

> import os
> os.system('シェルコマンド')
********* 結果の出力 *********
0
標準出力にコマンドの結果が表示され返り値として成功した場合は0,失敗した場合は0以外の数字が返される

2,「commands」ライブラリ(非推奨の手法)

> import commands
> result = commands.getoutput('シェルコマンド')
> print result
********* 結果の出力 *********
結果が返り値として出力されるそのため結果を変数に代入加工して使用することができる

3,「subprocess」ライブラリ(推奨の手法)

> import subprocess
> subprocess.call( ["ls", "-l"] )
********* 結果の出力 *********
0
標準出力にコマンドの結果が表示され返り値として成功した場合は0,失敗した場合は1が返される



> subprocess.check_call( ["ls", "-l"] )
********* 結果の出力 *********
0
標準出力にコマンドの結果が表示され返り値として成功した場合は0,失敗した場合は異常時には例外値を送出する



> result = subprocess.check_output(["ls", "-l"])
> print(result)
********* 結果の出力 *********
結果が返り値として出力されるそのため結果を変数に代入加工して使用することができ失敗した場合は異常時には例外値を送出する

python3によるシェルスクリプト実行

上記のうち、osライブラリとsubprocessライブラリを使用することができる。

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
61