71
59

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 5 years have passed since last update.

Pythonのsubprocessで標準出力をリアルタイムに取得する

Posted at

subprocessで実行したコマンドの標準出力を非同期で1行ずつ取得します。

  • Popen.stdout.readline() で標準出力をポーリング
  • 標準出力があれば yield で返す
  • Popen.poll() でプロセスの完了を検知
import sys
import subprocess


def get_lines(cmd):
    '''
    :param cmd: str 実行するコマンド.
    :rtype: generator
    :return: 標準出力 (行毎).
    '''
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    
    while True:
        line = proc.stdout.readline()
        if line:
            yield line
        
        if not line and proc.poll() is not None:
            break


if __name__ == '__main__':
    for line in get_lines(cmd='du ~/'):
        sys.stdout.write(line)
71
59
1

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
71
59

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?