From 1c5971955ec17f1e3c250e1d7813892beed12f24 Mon Sep 17 00:00:00 2001 From: SaeHie Park Date: Mon, 2 Sep 2024 23:48:15 +0000 Subject: [PATCH] [one-cmds] Introduce run_ret method in utils This will introduce run_ret method in utils which will return with process return code. ONE-DCO-1.0-Signed-off-by: SaeHie Park --- compiler/one-cmds/onelib/utils.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/compiler/one-cmds/onelib/utils.py b/compiler/one-cmds/onelib/utils.py index 7b9d193e7a0..c7ef184a184 100644 --- a/compiler/one-cmds/onelib/utils.py +++ b/compiler/one-cmds/onelib/utils.py @@ -187,6 +187,48 @@ def safemain(main, mainpath): sys.exit(255) +def run_ret(cmd, *, one_cmd: str = None, err_prefix=None, logfile=None): + """Execute command in subprocess + + Args: + one_cmd: subtool name to execute with given `cmd` + cmd: command to be executed in subprocess + err_prefix: prefix to be put before every stderr lines + logfile: file stream to which both of stdout and stderr lines will be written + Return: + Process execution return code; 0 if success and others for error. + """ + if one_cmd: + assert one_cmd in one_cmd_list(), f'Invalid ONE COMMAND: {one_cmd}' + dir_path = os.path.dirname(os.path.dirname( + os.path.realpath(__file__))) # bin = onelib/../ + driver_path = os.path.join(dir_path, f'one-{one_cmd}') + cmd = [driver_path] + cmd + + with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p: + import select + inputs = set([p.stdout, p.stderr]) + while inputs: + readable, _, _ = select.select(inputs, [], []) + for x in readable: + line = x.readline() + if len(line) == 0: + inputs.discard(x) + continue + if x == p.stdout: + out = sys.stdout + if x == p.stderr: + out = sys.stderr + if err_prefix: + line = f"{err_prefix}: ".encode() + line + out.buffer.write(line) + out.buffer.flush() + if logfile != None: + logfile.write(line) + return p.returncode + + +# TODO make run call run_ret def run(cmd, *, one_cmd: str = None, err_prefix=None, logfile=None): """Execute command in subprocess