-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.py
96 lines (79 loc) · 2.63 KB
/
runner.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from __future__ import print_function, unicode_literals
import os
import signal
import sys
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty
from subprocess import Popen, PIPE
from threading import Thread
from time import sleep
def _reader(stream, io_queue):
for line in iter(stream.readline, ''):
if line.endswith('\n'):
line = line[:-1]
io_queue.put(line)
if not stream.closed:
stream.close()
def _output_generator(io_queue, checker_thread):
while True:
try:
yield io_queue.get_nowait()
except Empty:
if not checker_thread.is_alive():
break
sleep(0.3)
def _printer(io_queue, checker_thread, postprocessor):
generator = _output_generator(io_queue, checker_thread)
if postprocessor:
generator = postprocessor(generator)
for line in generator:
print(line)
def _checker(process):
while True:
if process.poll() is not None:
break
sleep(0.5)
def run(args, cwd=None, postprocessor=None):
io_queue = Queue()
# Set environment, disabling Python buffering of the subprocess
env = os.environ.copy()
env['PYTHONUNBUFFERED'] = 'True'
# Set platform-specific arguments
kwargs = {}
if sys.platform == 'win32':
from subprocess import CREATE_NEW_PROCESS_GROUP
# Use a new process group
kwargs['creationflags'] = CREATE_NEW_PROCESS_GROUP
# Prevent "Terminate batch job (Y/N)?"
kwargs['stdin'] = open(os.devnull, 'r')
# Run process
process = Popen(
args, env=env, shell=True, stdout=PIPE, stderr=PIPE, **kwargs)
# Create and start all listening threads
stdout_thread = Thread(target=_reader, args=[process.stdout, io_queue])
stdin_thread = Thread(target=_reader, args=[process.stderr, io_queue])
checker_thread = Thread(target=_checker, args=[process])
printer_thread = Thread(target=_printer,
args=[io_queue, checker_thread, postprocessor])
stdout_thread.start()
stdin_thread.start()
checker_thread.start()
printer_thread.start()
# Wait for keyboard interrupt
while checker_thread.is_alive():
try:
sleep(0.5)
except KeyboardInterrupt:
break
# Gracefully terminate and show output from cleanup
term_signal = (
signal.CTRL_BREAK_EVENT if sys.platform == 'win32' else signal.SIGTERM)
while True:
try:
process.send_signal(term_signal)
printer_thread.join()
break
except KeyboardInterrupt:
continue