Debian Codegraph @

vmtest/asynciosubprocess.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import asyncio
5 from contextlib import contextmanager
6 import os
7 from subprocess import CalledProcessError as CalledProcessError
8 from typing import Any, Iterator, Tuple
9
10
11 async def check_call(*args: Any, **kwds: Any) -> None:
12 proc = await asyncio.create_subprocess_exec(*args, **kwds)
13 returncode = await proc.wait()
14 if returncode != 0:
15 raise CalledProcessError(returncode, args)
16
17
18 async def check_output(*args: Any, **kwds: Any) -> bytes:
19 kwds["stdout"] = asyncio.subprocess.PIPE
20 proc = await asyncio.create_subprocess_exec(*args, **kwds)
21 stdout = (await proc.communicate())[0]
22 if proc.returncode:
23 raise CalledProcessError(proc.returncode, args)
24 return stdout
25
26
27 async def check_output_shell(cmd: str, **kwds: Any) -> bytes:
28 kwds["stdout"] = asyncio.subprocess.PIPE
29 proc = await asyncio.create_subprocess_shell(cmd, **kwds)
30 stdout = (await proc.communicate())[0]
31 if proc.returncode:
32 raise CalledProcessError(proc.returncode, cmd)
33 return stdout
34
35
36 @contextmanager
37 def pipe_context() -> Iterator[Tuple[int, int]]:
38 pipe_r = pipe_w = None
39 try:
40 pipe_r, pipe_w = os.pipe()
41 yield pipe_r, pipe_w
42 finally:
43 if pipe_r is not None:
44 os.close(pipe_r)
45 if pipe_w is not None:
46 os.close(pipe_w)