3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonでOSのコマンドを実行して標準出力、標準エラー出力、リターンコードを取得する

Posted at

python3系で動作確認しました。

import subprocess


def exec_subprocess(cmd: str) -> (str, str, int):
    """
    OSコマンドを実行し結果を返す
    :param cmd: コマンド文字列
    :return: 標準出力、標準エラー出力、リターンコードのタプル
    """
    child = subprocess.Popen(cmd, shell=True,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = child.communicate()
    rt = child.returncode
    return stdout.decode(), stderr.decode(), rt

実行例1

stdout, stderr, rt = exec_subprocess("echo hello")

print(f"stdout={stdout}")
print(f"stderr={stderr}")
print(f"rt={rt}")

出力

stdout=hello

stderr=
rt=0

実行例2

stdout, stderr, rt = exec_subprocess("ls /hoge")

print(f"stdout={stdout}")
print(f"stderr={stderr}")
print(f"rt={rt}")

出力

stdout=
stderr=ls: /hoge: No such file or directory

rt=1
3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?