LoginSignup
2
2

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-04-09

前回の記事で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ではなくなりました。簡単に使えて楽だったので少し残念です。

2
2
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
2
2