promptflow
112 строк · 3.0 Кб
1import logging
2import os
3import subprocess
4import sys
5import time
6import traceback
7
8module_logger = logging.getLogger(__name__)
9
10
11class Color:
12PURPLE = "\033[95m"
13CYAN = "\033[96m"
14DARKCYAN = "\033[36m"
15BLUE = "\033[94m"
16GREEN = "\033[92m"
17YELLOW = "\033[93m"
18RED = "\033[91m"
19BOLD = "\033[1m"
20UNDERLINE = "\033[4m"
21END = "\033[0m"
22
23
24def print_red(message):
25print(Color.RED + message + Color.END)
26
27
28def print_blue(message):
29print(Color.BLUE + message + Color.END)
30
31
32def get_test_files(testpath):
33if os.path.isfile(testpath):
34return [testpath]
35else:
36res = []
37for root, dirs, files in os.walk(testpath):
38module_logger.debug("Searching %s for files ending in 'tests.py'", root)
39res.extend([os.path.join(root, file) for file in files if file.endswith("tests.py")])
40return res
41
42
43def retry(fn, num_attempts=3):
44if num_attempts <= 0:
45raise Exception("Illegal num_attempts: {}".format(num_attempts))
46count = 0
47for _ in range(0, num_attempts):
48try:
49return fn()
50except Exception:
51count += 1
52print("Execution failed on attempt {} out of {}".format(count, num_attempts))
53print("Exception trace:")
54traceback.print_exc()
55if count == num_attempts:
56print("Execution failed after {} attempts".format(count))
57raise
58
59
60def _run_command(
61commands,
62cwd=None,
63stderr=subprocess.STDOUT,
64shell=False,
65env=None,
66stream_stdout=True,
67throw_on_retcode=True,
68logger=None,
69):
70if logger is None:
71logger = module_logger
72
73if cwd is None:
74cwd = os.getcwd()
75
76t0 = time.perf_counter()
77try:
78logger.debug("[RunCommand]Executing {0} in {1}".format(commands, cwd))
79out = ""
80p = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd, shell=shell, env=env)
81for line in p.stdout:
82line = line.decode("utf-8").rstrip()
83if line and line.strip():
84logger.debug(line)
85if stream_stdout:
86sys.stdout.write(line)
87sys.stdout.write("\n")
88out += line
89out += "\n"
90p.communicate()
91retcode = p.poll()
92if throw_on_retcode:
93if retcode:
94raise subprocess.CalledProcessError(retcode, p.args, output=out, stderr=p.stderr)
95return retcode, out
96finally:
97t1 = time.perf_counter()
98logger.debug("[RunCommand] Execution took {0}s for {1} in {2}".format(t1 - t0, commands, cwd))
99
100
101def run_command(
102commands, cwd=None, stderr=subprocess.STDOUT, shell=False, stream_stdout=True, throw_on_retcode=True, logger=None
103):
104return _run_command(
105commands,
106cwd=cwd,
107stderr=stderr,
108shell=shell,
109stream_stdout=stream_stdout,
110throw_on_retcode=throw_on_retcode,
111logger=logger,
112)
113