【Python】 pythonからshellの実行

Pythonからshellコマンドを実行する際に以下のようなやり方がある.
今回は次のshellコマンドをpythonで実行するやり方を比較する.

$sha256sum hoge.zip
#返り値:  xxxxxxxxxxx hoge.zip

os.system()を使う方法

import os
file_name = "hoge.zip"
os.system('sha256sum "{}"'.format(file_name))
# 成功
# xxxxxxxxxxx hoge.zip
# 0
# 失敗
# sha256sum: hoge.zip : No such file or directory
# 256

成功したか失敗したかのみしかわからない.
コマンドの出力が受け取れないし, 推奨されていないやり方らしい.

subprocess.check_output()を使う方法

import subprocess
file_name = "hoge.zip"
args = ["sha256sum", file_name]
subprocess.check_output(args)
# 成功
# b'16e3a87f14dce201f90dc0f7dd2a6318e7b9e5aef095e5815123c3a44e92ac97  GA_result.txt\n'
# 失敗
# sha256sum: hoge.zip : No such file or directory
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#  File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 316, in check_output  **kwargs).stdout
#  File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 398, in run output=stdout, stderr=stderr)
# subprocess.CalledProcessError: Command '['sha256sum', 'GA_result1.txt']' returned non-zero exit status 1

成功した場合, 返り値はbyte型なのでstr型にdecodeし, pythonコード内でshellの出力結果を得ることができる.

res = subprocess.check_output(args)
hash_value = res.decode("utf-8").split(" ")[0]

ただし, windowsの場合はうまく行かない可能性がある. 原因はまだ良く見てない.

commands.getstatusoutput()を使う方法

昔よく使っていたが, Python3 で廃止されたらしい.
これの代用がsubprocessモジュールになったらしい.