You can use subprocess.PIPE in subprocess to get the standard output, but it will not appear in the Console.
I wanted to get it as str while displaying it in real time on the Console, so I tried to find out how to do it.
This one using yield is better.
Code
import sys
import subprocess
def run_and_capture(cmd):
'''
:param cmd:str command to execute.
:rtype: str
:return:Standard output.
'''
#Here the process(Asynchronously)Start.
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
buf = []
while True:
#Read one line from the buffer.
line = proc.stdout.readline()
buf.append(line)
sys.stdout.write(line)
#Buffer is empty+End of process.
if not line and proc.poll() is not None:
break
return ''.join(buf)
if __name__ == '__main__':
msg = run_and_capture('du ~/')
print msg
subprocess.Popen (cmd, ...) stderr = subprocess.STDOUT to bundle stderr into stdout stdout = subprocess.PIPEPopen.stdout.readline () line by line''. Join (buf) Recommended Posts