-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbetter_console.py
More file actions
32 lines (24 loc) · 847 Bytes
/
better_console.py
File metadata and controls
32 lines (24 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
""" A demo of better console output using regex """
import re
import time
from subprocess import Popen, PIPE
SHOW_ORIGINAL_OUTPUT = False
REGEX_OUT = r"(.*)"
pat = re.compile(REGEX_OUT)
orig = time.time()
p = Popen(["python", "company_name_maker.py"], stdout=PIPE)
# Grab stdout line by line as it becomes available.
# This will loop until p terminates.
print("Listening to process...\n")
while p.poll() is None:
# Blocks until it receives a newline.
l = str(p.stdout.readline().decode('utf-8'))
if (SHOW_ORIGINAL_OUTPUT):
print(l)
else:
m = pat.match(l)
if m is not None:
print('[{:.2f}] '.format(time.time()-orig) + m.group(1))
# When the subprocess terminates there might be unconsumed output
# that still needs to be processed.
print(p.stdout.read())