process.py 1.67 KB
Newer Older
1
2
3
4
5
6
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Process Utility."""

import subprocess
7
8
import os
import shlex
9

10
from superbench.common.utils import stdout_logger
11

12
13

def run_command(command, quite=False, flush_output=False):
14
15
16
17
    """Run command in string format, return the result with stdout and stderr.

    Args:
        command (str): command to run.
18
19
        quite (bool): no stdout display of the command if quite is True.
        flush_output (bool): enable real-time output flush or not when running the command.
20
21
22
23

    Return:
        result (subprocess.CompletedProcess): The return value from subprocess.run().
    """
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
    if flush_output:
        process = None
        try:
            args = shlex.split(command)
            process = subprocess.Popen(
                args, cwd=os.getcwd(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True
            )
            output = ''
            for line in process.stdout:
                output += line
                if not quite:
                    stdout_logger.log(line)
            process.wait()
            retcode = process.poll()
            return subprocess.CompletedProcess(args=args, returncode=retcode, stdout=output)
        except Exception as e:
            if process:
                process.kill()
                process.wait()
            return subprocess.CompletedProcess(args=args, returncode=-1, stdout=str(e))
    else:
        result = subprocess.run(
            command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, check=False, universal_newlines=True
        )
        if not quite:
            stdout_logger.log(result.stdout)
        return result