Home Assistant Unofficial Reference 2024.12.1
utils.py
Go to the documentation of this file.
1 """The command_line component utils."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 import logging
7 
8 _LOGGER = logging.getLogger(__name__)
9 _EXEC_FAILED_CODE = 127
10 
11 
13  command: str, timeout: int, *, log_return_code: bool = True
14 ) -> int:
15  """Run a shell command with a timeout.
16 
17  If log_return_code is set to False, it will not print an error if a non-zero
18  return code is returned.
19  """
20  try:
21  _LOGGER.debug("Running command: %s", command)
22  proc = await asyncio.create_subprocess_shell( # shell by design
23  command,
24  close_fds=False, # required for posix_spawn
25  )
26  async with asyncio.timeout(timeout):
27  await proc.communicate()
28  except TimeoutError:
29  _LOGGER.error("Timeout for command: %s", command)
30  return -1
31 
32  return_code = proc.returncode
33  if return_code == _EXEC_FAILED_CODE:
34  _LOGGER.error("Error trying to exec command: %s", command)
35  elif log_return_code and return_code != 0:
36  _LOGGER.error(
37  "Command failed (with return code %s): %s",
38  proc.returncode,
39  command,
40  )
41  return return_code or 0
42 
43 
44 async def async_check_output_or_log(command: str, timeout: int) -> str | None:
45  """Run a shell command with a timeout and return the output."""
46  try:
47  proc = await asyncio.create_subprocess_shell( # shell by design
48  command,
49  close_fds=False, # required for posix_spawn
50  stdout=asyncio.subprocess.PIPE,
51  )
52  async with asyncio.timeout(timeout):
53  stdout, _ = await proc.communicate()
54 
55  if proc.returncode != 0:
56  _LOGGER.error(
57  "Command failed (with return code %s): %s", proc.returncode, command
58  )
59  else:
60  return stdout.strip().decode("utf-8")
61  except TimeoutError:
62  _LOGGER.error("Timeout for command: %s", command)
63 
64  return None
int async_call_shell_with_timeout(str command, int timeout, *bool log_return_code=True)
Definition: utils.py:14
str|None async_check_output_or_log(str command, int timeout)
Definition: utils.py:44