uwtools.api.utils

API access to utility functions.

uwtools.api.utils.atomic(path)

Yields a path to a temporary file, finally renaming that file to path.

Parameters:

path (Path) – The final path.

Yields:

The path to a temporary file.

Yieldtype:

Path.

Return type:

Iterator[Path]

uwtools.api.utils.run_shell_cmd(cmd, callback=None, cwd=None, env=None, executable=None, log_output=False, quiet=False, start_new_session=False, taskname=None)

Run a command in a shell.

Parameters:
  • cmd (str | list[str]) – The command to run.

  • callback (Callable[[Popen], None] | None) – Called with the Popen process object.

  • cwd (Path | str | None) – Change to this directory before running the command.

  • env (dict[str, str] | None) – Environment variables to set before running the command.

  • executable (str | None) – Interpreter to run command in (e.g. “/bin/bash”).

  • log_output (bool) – Log output from successful command? (Error output is always logged.)

  • quiet (bool) – Log INFO messages as DEBUG.

  • start_new_session (bool) – Run process in a new session?

  • taskname (str | None) – Name of task executing this command, for logging.

Returns:

Success indication and combined stdout / stderr.

Return type:

tuple[bool, str]

The Callable specified by the callback argument will be called once with the Popen object as soon as it is available; i.e. it may be called while the command is running, and does not wait for the command to complete.

Use executable to use a shell other than the subprocess.Popen default, /bin/sh.

It is assumed that uwtools.api.loggin.use_uwtools_logger has previously been called to set up logging if log_output is True.

The start_new_session argument is connected directly to the argument of the same name when subprocess.Popen is called. Among other potential use cases, it prevents the command from receiving a SIGINT generated by a user Ctrl-C, useful when the command is running in a thread and the main control thread should handle the interrupt.

If taskname is provided, log messages will be prefixed with [<taskname>].