2021-12-03 08:33:16 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
from subprocess import Popen, PIPE, STDOUT
|
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
# Very simple tee logic implementation. You can specify shell command, output
|
|
|
|
# logfile and env variables. After TeePopen is created you can only wait until
|
|
|
|
# it finishes. stderr and stdout will be redirected both to specified file and
|
|
|
|
# stdout.
|
|
|
|
class TeePopen:
|
2021-12-03 09:19:39 +00:00
|
|
|
# pylint: disable=W0102
|
2022-02-15 15:38:33 +00:00
|
|
|
def __init__(self, command, log_file, env=os.environ.copy(), timeout=None):
|
2021-12-03 08:33:16 +00:00
|
|
|
self.command = command
|
|
|
|
self.log_file = log_file
|
|
|
|
self.env = env
|
2022-01-11 11:23:09 +00:00
|
|
|
self.process = None
|
2022-02-15 15:38:33 +00:00
|
|
|
self.timeout = timeout
|
2021-12-03 08:33:16 +00:00
|
|
|
|
|
|
|
def __enter__(self):
|
2022-01-11 11:23:09 +00:00
|
|
|
self.process = Popen(
|
|
|
|
self.command,
|
|
|
|
shell=True,
|
|
|
|
universal_newlines=True,
|
|
|
|
env=self.env,
|
|
|
|
stderr=STDOUT,
|
|
|
|
stdout=PIPE,
|
|
|
|
bufsize=1,
|
|
|
|
)
|
|
|
|
self.log_file = open(self.log_file, "w", encoding="utf-8")
|
2021-12-03 08:33:16 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, t, value, traceback):
|
|
|
|
for line in self.process.stdout:
|
|
|
|
sys.stdout.write(line)
|
|
|
|
self.log_file.write(line)
|
|
|
|
|
2022-02-15 15:38:33 +00:00
|
|
|
self.process.wait(self.timeout)
|
2021-12-03 08:33:16 +00:00
|
|
|
self.log_file.close()
|
|
|
|
|
|
|
|
def wait(self):
|
|
|
|
for line in self.process.stdout:
|
|
|
|
sys.stdout.write(line)
|
|
|
|
self.log_file.write(line)
|
|
|
|
|
2022-02-15 15:38:33 +00:00
|
|
|
return self.process.wait(self.timeout)
|