process.py 1.93 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, quiet=False, flush_output=False, cwd=None):
14
15
16
17
    """Run command in string format, return the result with stdout and stderr.

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

    Return:
        result (subprocess.CompletedProcess): The return value from subprocess.run().
    """
25
26
27
28
29
    if flush_output:
        process = None
        try:
            args = shlex.split(command)
            process = subprocess.Popen(
30
31
32
33
34
                args,
                cwd=os.getcwd() if cwd is None else cwd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                universal_newlines=True
35
36
37
38
            )
            output = ''
            for line in process.stdout:
                output += line
39
                if not quiet:
40
41
42
43
44
45
46
47
48
49
50
                    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(
51
52
53
54
55
56
57
            command,
            cwd=os.getcwd() if cwd is None else cwd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=True,
            check=False,
            universal_newlines=True
58
        )
59
        if not quiet:
60
61
            stdout_logger.log(result.stdout)
        return result