I guess it's 2023 now...
[pyutils.git] / src / pyutils / misc_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2023, 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     Args:
35         probability_to_execute: the probability of returning True.
36
37     Returns:
38         True with a given probability.
39
40     >>> random.seed(22)
41     >>> execute_probabilistically(50.0)
42     False
43     >>> execute_probabilistically(50.0)
44     True
45
46     """
47     return random.uniform(0.0, 100.0) < probability_to_execute
48
49
50 if __name__ == "__main__":
51     import doctest
52
53     doctest.testmod()