Skip to content

Instantly share code, notes, and snippets.

@takp
Created February 27, 2019 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takp/adf59663bf4c49a4af9e4b60df2a7591 to your computer and use it in GitHub Desktop.
Save takp/adf59663bf4c49a4af9e4b60df2a7591 to your computer and use it in GitHub Desktop.
import sys
import subprocess
def execute_subprocess(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
line = process.stdout.readline()
if line:
yield line
if not line and process.poll() is not None:
break
if __name__ == '__main__':
command = 'ls -l'
prefix = 'INFO'
for line in execute_subprocess(command=command):
log_output = "[{}] {}".format(prefix, line.decode('utf8'))
sys.stdout.write(log_output)
@takp
Copy link
Author

takp commented Feb 27, 2019

  • This is the example code to execute ls -l command with subprocess.

  • Sample output that adds [INFO] to the stdout:

# python  modify-subprocess-stdout.py
[INFO] total 40
[INFO] -rw-r--r--  1 root root 1090 Feb 21 03:27 Dockerfile
[INFO] -rw-r--r--  1 root root 1573 Feb 21 03:27 README.md
[INFO] drwxr-xr-x  7 root root  224 Feb 27 06:54 app
[INFO] drwxr-xr-x  8 root root  256 Feb 27 16:39 config

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment