あるフリーランスエンジニアの色んなメモ!! ITスキル・ライフハックとか

Python:OSコマンドを実行する

その1

import shlex, subprocess

returncode = subprocess.call(shlex.split('実行コマンド'))

※Python 3.5 より前のバージョンでも使用可能 ※終了コードが取得可能

参考

https://docs.python.org/ja/3/library/subprocess.html#subprocess.call


その2

import os

returncode = os.system('実行コマンド')

※実行コマンドの出力は標準出力に出力される
※終了コードが取得可能


その3

import os

result = os.popen('実行コマンド')
returncode = 0 if result.close() is None else result.close()
stdout = result.read().rstrip('\n')

※終了コード、標準出力が取得可能


その4

import subprocess

result = subprocess.run(実行コマンド(list型))

# 終了コード
result.returncode

# 標準出力
result.stdout

※Python3.5から使用可能 ※終了コード、標準出力等が取得可能

参考

https://docs.python.org/ja/3/library/subprocess.html#subprocess.run
https://docs.python.org/ja/3/library/subprocess.html#subprocess.CompletedProcess

comments powered by Disqus