LoginSignup
11
8

More than 3 years have passed since last update.

pythonのsubprocessで標準出力を文字列として受け取る

Last updated at Posted at 2021-02-21

概要

pythonでsubprocessを使って処理を行なった後,標準出力を文字列として受け取りたいことがあります.
ちょくちょく行う処理なのですが,いつもどうやるのか忘れるのでメモしておきます.

version

python3.9.2
(python3.7以降は同じ)

やり方

subprocessの実行は最近(python3.5以降)では公式ドキュメントによるとsubprocess.runを使うのが良いみたいです.
一発で標準出力を文字列として受け取るには以下のようにします.

>>> import subprocess
>>> output_str = subprocess.run('ls', capture_output=True, text=True).stdout

('ls'は実行したいコマンドの例です.)

その結果,

>>> print(output_str)
'Dockerfile\nLICENSE\nREADME.md\nsrc\n'
>>> print(type(output_str))
<class 'str'>

標準出力を文字列として受け取ることができています!

capture_output=Trueで出力が受け取れるようになり,
text=Trueを渡すことで出力をバイナリではなく文字列として返してくれるようになります.

さらにsubprocess.runCompletedProcessというクラスを返すのですが,
そのクラスの変数であるstdoutにアクセスすることで標準出力を受け取っています.

>>> subprocess.run('ls', capture_output=True, text=True)
CompletedProcess(args='ls', returncode=0, stdout='Dockerfile\nDockerfile:cpu\nDockerfile:cuda10.2-cudnn7\nLICENSE\nREADME.md\ndata\nresult\nsrc\ntrained_model.npz\n', stderr='')

標準エラー出力や戻り値にアクセスしたい場合はそれぞれstderr, returncodeにアクセスすれば良いです.

11
8
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
11
8