2
1

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のsubprocessから実行結果を取得する

Posted at

pythonのsubprocessから実行結果を取得する時のメモ

試したバージョンは以下の通り

$ python --version
Python 3.7.1

subprocess.runを使う場合は以下のようにすれば良い

test.py
import subprocess
ret = subprocess.run("python --version", shell=True, stdout=subprocess.PIPE , stderr=subprocess.PIPE ,encoding="utf-8")
print(ret)
if "Python 2" in ret.stdout:
    print("python")
if "Python 3" in ret.stdout:
    print("python3")

実行結果

$ python test.py
CompletedProcess(args='python --version', returncode=0, stdout='Python 3.7.1\n', stderr='')
python3

参考

python で subprocess を使ってコマンドを実行する方法
標準エラー出力へ出力する (sys.stderr)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?