Acquires the standard output of the command executed by subprocess asynchronously line by line.
Popen.stdout.readline ()
yield
Popen.poll ()
detects process completionimport sys
import subprocess
def get_lines(cmd):
'''
:param cmd:str command to execute.
:rtype: generator
:return:Standard output(Line by line).
'''
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)
Recommended Posts