stouputils.ctx module#

This module provides context managers for various utilities such as logging to a file, measuring execution time, silencing output, and setting multiprocessing start methods.

  • LogToFile: Context manager to log to a file every print call (with LINE_UP handling)

  • MeasureTime: Context manager to measure execution time of a code block

  • Muffle: Context manager that temporarily silences output (alternative to stouputils.decorators.silent())

  • DoNothing: Context manager that does nothing (no-op)

  • SetMPStartMethod: Context manager to temporarily set multiprocessing start method

stouputils ctx examples
class AbstractBothContextManager[source]#

Bases: AbstractContextManager, AbstractAsyncContextManager, Generic

Abstract base class for context managers that support both synchronous and asynchronous usage.

_abc_impl = <_abc._abc_data object>#
class LogToFile(
path: str,
mode: str = 'w',
encoding: str = 'utf-8',
tee_stdout: bool = True,
tee_stderr: bool = True,
ignore_lineup: bool = True,
restore_on_exit: bool = False,
)[source]#

Bases: AbstractBothContextManager[LogToFile]

Context manager to log to a file.

This context manager allows you to temporarily log output to a file while still printing normally. The file will receive log messages without ANSI color codes.

Parameters:
  • path (str) – Path to the log file

  • mode (str) – Mode to open the file in (default: “w”)

  • encoding (str) – Encoding to use for the file (default: “utf-8”)

  • tee_stdout (bool) – Whether to redirect stdout to the file (default: True)

  • tee_stderr (bool) – Whether to redirect stderr to the file (default: True)

  • ignore_lineup (bool) – Whether to ignore lines containing LINE_UP escape sequence in files (default: False)

  • restore_on_exit (bool) – Whether to restore original stdout/stderr on exit (default: False) This ctx uses TeeMultiOutput which handles closed files gracefully, so restoring is not mandatory.

Examples

> import stouputils as stp
> with stp.LogToFile("output.log"):
>     stp.info("This will be logged to output.log and printed normally")
>     print("This will also be logged")

> with stp.LogToFile("output.log") as log_ctx:
>     stp.warning("This will be logged to output.log and printed normally")
>     log_ctx.change_file("new_file.log")
>     print("This will be logged to new_file.log")
path: str#

Attribute remembering path to the log file

mode: str#

Attribute remembering mode to open the file in

encoding: str#

Attribute remembering encoding to use for the file

tee_stdout: bool#

Whether to redirect stdout to the file

tee_stderr: bool#

Whether to redirect stderr to the file

ignore_lineup: bool#

Whether to ignore lines containing LINE_UP escape sequence in files

restore_on_exit: bool#

Whether to restore original stdout/stderr on exit. This ctx uses TeeMultiOutput which handles closed files gracefully, so restoring is not mandatory.

file: IO[Any]#

Attribute remembering opened file

original_stdout: TextIO#

Original stdout before redirection

original_stderr: TextIO#

Original stderr before redirection

change_file(new_path: str) None[source]#

Change the log file to a new path.

Parameters:

new_path (str) – New path to the log file

static common(
logs_folder: str,
filepath: str,
func: Callable[[...], Any],
*args: Any,
**kwargs: Any,
) Any[source]#

Common code used at the beginning of a program to launch main function

Parameters:
  • logs_folder (str) – Folder to store logs in

  • filepath (str) – Path to the main function

  • func (Callable[..., Any]) – Main function to launch

  • *args (tuple[Any, ...]) – Arguments to pass to the main function

  • **kwargs (dict[str, Any]) – Keyword arguments to pass to the main function

Returns:

Return value of the main function

Return type:

Any

Examples

>>> if __name__ == "__main__":
...     LogToFile.common(f"{ROOT}/logs", __file__, main)
_abc_impl = <_abc._abc_data object>#
class MeasureTime(print_func: ~collections.abc.Callable[[...], None] = <function debug>, message: str = 'Execution time', perf_counter: bool = True)[source]#

Bases: AbstractBothContextManager[MeasureTime]

Context manager to measure execution time.

This context manager measures the execution time of the code block it wraps and prints the result using a specified print function.

Parameters:
  • print_func (Callable) – Function to use to print the execution time (e.g. debug, info, warning, error, etc.).

  • message (str) – Message to display with the execution time. Defaults to “Execution time”.

  • perf_counter (bool) – Whether to use time.perf_counter_ns or time.time_ns. Defaults to True.

Examples

> import time
> import stouputils as stp
> with stp.MeasureTime(stp.info, message="My operation"):
...     time.sleep(0.5)
> # [INFO HH:MM:SS] My operation: 500.123ms (500123456ns)

> with stp.MeasureTime(): # Uses debug by default
...     time.sleep(0.1)
> # [DEBUG HH:MM:SS] Execution time: 100.456ms (100456789ns)
print_func: Callable[[...], None]#

Function to use for printing the execution time

message: str#

Message to display with the execution time

perf_counter: bool#

Whether to use time.perf_counter_ns or time.time_ns

ns: Callable[[], int]#

Time function to use

start_ns: int#

Start time in nanoseconds

_abc_impl = <_abc._abc_data object>#
class Muffle(mute_stderr: bool = False)[source]#

Bases: AbstractBothContextManager[Muffle]

Context manager that temporarily silences output. (No thread-safety guaranteed)

Alternative to stouputils.decorators.silent()

Examples

>>> with Muffle():
...     print("This will not be printed")
mute_stderr: bool#

Attribute remembering if stderr should be muted

original_stdout: IO[Any]#

Attribute remembering original stdout

original_stderr: IO[Any]#

Attribute remembering original stderr

_abc_impl = <_abc._abc_data object>#
class DoNothing(*args: Any, **kwargs: Any)[source]#

Bases: AbstractBothContextManager[DoNothing]

Context manager that does nothing.

This is a no-op context manager that can be used as a placeholder or for conditional context management.

Different from contextlib.nullcontext because it handles args and kwargs, along with async context management.

Examples

>>> with DoNothing():
...     print("This will be printed normally")
This will be printed normally
>>> # Conditional context management
>>> some_condition = True
>>> ctx = DoNothing() if some_condition else Muffle()
>>> with ctx:
...     print("May or may not be printed depending on condition")
May or may not be printed depending on condition
_abc_impl = <_abc._abc_data object>#
NullContextManager#

Alias for DoNothing context manager

class SetMPStartMethod(start_method: str | None)[source]#

Bases: AbstractBothContextManager[SetMPStartMethod]

Context manager to temporarily set multiprocessing start method.

This context manager allows you to temporarily change the multiprocessing start method and automatically restores the original method when exiting the context.

Parameters:

start_method (str) – The start method to use: “spawn”, “fork”, or “forkserver”

Examples

> import multiprocessing as mp
> import stouputils as stp
> # Temporarily use spawn method
> with stp.SetMPStartMethod("spawn"):
> ...     # Your multiprocessing code here
> ...     pass

> # Original method is automatically restored
_abc_impl = <_abc._abc_data object>#
start_method: str | None#

The start method to use

old_method: str | None#

The original start method to restore