Convert to a string while outputting standard output with Python subprocess

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.

--Addition--

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

Description

  1. Start the process with subprocess.Popen (cmd, ...)
  1. Get and output the standard output piped by Popen.stdout.readline () line by line
  2. Collect all piped standard output + wait for process to complete
  3. Join strings with ''. Join (buf)

Recommended Posts

Convert to a string while outputting standard output with Python subprocess
How to convert / restore a string with [] in python
[python] Convert date to string
Get standard output in real time with Python subprocess
How to convert an array to a dictionary with Python [Application]
Change the standard output destination to a file in Python
Python learning basics ~ How to output (display) a character string? ~
Create a message corresponding to localization with python translation string
Output to csv file with Python
Write standard output to a file
Convert list to DataFrame with python
Convert a string to an image
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to output a character string in a Print statement
Try to extract a character string from an image with Python3
Read the standard output of a subprocess line by line in Python
When you want to print to standard output with print while testing with pytest
Convert memo at once with Python 2to3
Output color characters to pretty with python
[Python] How to convert a 2D list to a 1D list
Output Python log to console with GAE
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
[Python] How to invert a character string
Convert FX 1-minute data to 5-minute data with Python
UnicodeEncodeError struggle with standard output of python3
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Sample to convert image to Wavelet with Python
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
Note: [Python3] Convert datetime to a string in any format you like
Mayungo's Python Learning Episode 6: I tried to convert a character string to a number
[Introduction to Python] How to write a character string with the format function
How to read a CSV file with Python 2/3
Scraping tabelog with python and outputting to CSV
Send a message to LINE with Python (LINE Notify)
Convert PDF to image (JPEG / PNG) with Python
How to embed a variable in a python string
Convert PDFs to images in bulk with Python
Try to draw a life curve with python
I want to make a game with Python
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
Try to make a "cryptanalysis" cipher with Python
I tried to output LLVM IR with Python
Decide to assign a laboratory with Python (fiction)
Python Note: When assigning a value to a string
Steps to create a Twitter bot with python
Try to make a dihedral group with Python
How to output "Ketsumaimo" as standard output in Python
Decrypt a string encrypted on iOS with Python
I want to write to a file with Python
A layman wants to get started with Python
[CentOS8] How to output Python standard output to systemd log
Convert strings to character-by-character list format with python
Convert the world time zone time string to Japan time without calculating the time difference with python.
Output timing is incorrect when standard (error) output is converted to a file in Python
[Tentative] How to convert a character string to Shift_jis with kivy-ios Memo kivy v1.8.0
Make one repeating string with a Python regular expression.
Run the output code with tkinter, saying "A, pretending to be B" in python
Parse a JSON string written to a file in Python