this repo has no description
1#!/usr/bin/env python3
2# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
3
4import shlex
5import subprocess
6import sys
7import textwrap
8
9
10def with_pty(command):
11 return [sys.executable, "-c", "import pty, sys; pty.spawn(sys.argv[1:])"] + command
12
13
14def run(
15 cmd,
16 verbose=True,
17 cwd=None,
18 check=True,
19 capture_output=False,
20 encoding="utf-8",
21 # Specify an integer number of seconds
22 timeout=-1,
23 **kwargs,
24):
25 if verbose:
26 info = "$ "
27 if cwd is not None:
28 info += f"cd {cwd}; "
29 info += " ".join(shlex.quote(c) for c in cmd)
30 if capture_output:
31 info += " >& ..."
32 lines = textwrap.wrap(
33 info,
34 break_on_hyphens=False,
35 break_long_words=False,
36 replace_whitespace=False,
37 subsequent_indent=" ",
38 )
39 print(" \\\n".join(lines))
40 if timeout != -1:
41 cmd = ["timeout", "--signal=KILL", f"{timeout}s", *cmd]
42 try:
43 return subprocess.run(
44 cmd,
45 cwd=cwd,
46 check=check,
47 capture_output=capture_output,
48 encoding=encoding,
49 **kwargs,
50 )
51 except subprocess.CalledProcessError as e:
52 if e.returncode == -9:
53 # Error code from `timeout` command signaling it had to be killed
54 raise TimeoutError("Command timed out", cmd)
55 raise