前回の記事でPython3からシェルスクリプトを実行するテストを紹介しました。
今回はPythonでシェルスクリプトを実行する方法についてPython2.xとPython3.xの違いを中心にまとめます。
Python 2.x
os.system('ls -al')
コマンドが成功すれば0が返ってきます。
import os
status = os.system('ls -al')
print status
commands.getoutput('ls -al')
実際に実行した結果が返ってきます。
import commands
res = commands.getoutput('ls -al')
print res
Python 3.x
subprocess.run
os.systemより発展されたもの。コマンドの戻り値を色々設定出来ます。一番良く使うパターンはこんな感じ。
import subprocess
res = subprocess.run(
['ls', '-al’], stderr=subprocess.PIPE)
print(res.stderr)
subprocessの使い方は色々あります。
以下の記事などご参考ください。
ref. subprocessの使い方(Python3.6)
commands.getoutput
3.xではなくなりました。簡単に使えて楽だったので少し残念です。