Skip to content

Commit 6361e87

Browse files
committed
update
1 parent 8388e81 commit 6361e87

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

tools/python/util/run.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
from __future__ import annotations
4+
5+
import logging
6+
import os
7+
import shlex
8+
import subprocess
9+
10+
_log = logging.getLogger("util.run")
11+
12+
13+
def run(
14+
*args,
15+
cwd=None,
16+
input=None,
17+
capture_stdout=False,
18+
capture_stderr=False,
19+
shell=False,
20+
env=None,
21+
check=True,
22+
quiet=False,
23+
):
24+
"""Runs a subprocess.
25+
26+
Args:
27+
*args: The subprocess arguments.
28+
cwd: The working directory. If None, specifies the current directory.
29+
input: The optional input byte sequence.
30+
capture_stdout: Whether to capture stdout.
31+
capture_stderr: Whether to capture stderr.
32+
shell: Whether to run using the shell.
33+
env: The environment variables as a dict. If None, inherits the current
34+
environment.
35+
check: Whether to raise an error if the return code is not zero.
36+
quiet: If true, do not print output from the subprocess.
37+
38+
Returns:
39+
A subprocess.CompletedProcess instance.
40+
"""
41+
cmd = [*args]
42+
43+
_log.info(
44+
"Running subprocess in '{}'\n {}".format(cwd or os.getcwd(), " ".join([shlex.quote(arg) for arg in cmd]))
45+
)
46+
47+
def output(is_stream_captured):
48+
return subprocess.PIPE if is_stream_captured else (subprocess.DEVNULL if quiet else None)
49+
50+
completed_process = subprocess.run(
51+
cmd,
52+
cwd=cwd,
53+
check=check,
54+
input=input,
55+
stdout=output(capture_stdout),
56+
stderr=output(capture_stderr),
57+
env=env,
58+
shell=shell,
59+
)
60+
61+
_log.debug(f"Subprocess completed. Return code: {completed_process.returncode}")
62+
63+
return completed_process

0 commit comments

Comments
 (0)