Adds execute_probabilistically.
[pyutils.git] / src / pyutils / misc_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """Miscellaneous utilities."""
6
7 import os
8 import random
9 import sys
10
11
12 def is_running_as_root() -> bool:
13     """
14     Returns:
15         True if running as root, False otherwise.
16
17     >>> is_running_as_root()
18     False
19     """
20     return os.geteuid() == 0
21
22
23 def debugger_is_attached() -> bool:
24     """
25     Returns:
26         True if a debugger is attached, False otherwise.
27     """
28     gettrace = getattr(sys, "gettrace", lambda: None)
29     return gettrace() is not None
30
31
32 def execute_probabilistically(probability_to_execute: float) -> bool:
33     """
34     Returns:
35         True with a given probability.
36     """
37     return random.uniform(0.0, 100.0) < probability_to_execute
38
39
40 if __name__ == "__main__":
41     import doctest
42
43     doctest.testmod()