easy-exit-calls 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- easy_exit_calls-1.0.0/LICENSE.md +19 -0
- easy_exit_calls-1.0.0/PKG-INFO +167 -0
- easy_exit_calls-1.0.0/README.md +144 -0
- easy_exit_calls-1.0.0/easy_exit_calls/__init__.py +33 -0
- easy_exit_calls-1.0.0/easy_exit_calls/classes.py +479 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/__init__.py +5 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/__init__.py +9 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/author/__init__.py +10 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/author/contributors/CONTRIB_TEMPLATE.json +52 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/author/contributors/__init__.py +2 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/author/main/__init__.py +2 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/author/software_org/__init__.py +8 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/package/__init__.py +7 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/package/version/__VERSION__ +2 -0
- easy_exit_calls-1.0.0/easy_exit_calls/common/meta/package/version/__init__.py +13 -0
- easy_exit_calls-1.0.0/easy_exit_calls/decorator.py +50 -0
- easy_exit_calls-1.0.0/easy_exit_calls/example_helpers.py +71 -0
- easy_exit_calls-1.0.0/easy_exit_calls/helpers/__init__.py +6 -0
- easy_exit_calls-1.0.0/easy_exit_calls/helpers/decorator.py +50 -0
- easy_exit_calls-1.0.0/easy_exit_calls/helpers/handler_list.py +123 -0
- easy_exit_calls-1.0.0/easy_exit_calls/log_engine.py +12 -0
- easy_exit_calls-1.0.0/pyproject.toml +35 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2025 **Inspyre-Softworks**
|
|
2
|
+
|
|
3
|
+
Permission is **hereby granted**, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software (*EasyExitCalls*) and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including **without limitation** the rights
|
|
6
|
+
to *use*, *copy*, *modify*, *merge*, *publish*, *distribute*, **sub***license*, **and**/**or** *sell*
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, **subject to the following conditions**:
|
|
9
|
+
|
|
10
|
+
*The above copyright notice and this permission notice shall be included in **all
|
|
11
|
+
copies** or substantial portions of the Software.*
|
|
12
|
+
|
|
13
|
+
**THE SOFTWARE IS PROVIDED **"*AS IS*"**, WITHOUT WARRANTY OF ANY KIND, *EXPRESS* OR
|
|
14
|
+
*IMPLIED*, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR *ANY CLAIM*, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.**
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: easy-exit-calls
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A Python library for managing exit handlers with enhanced features like decorators, UUID tracking, and LIFO execution.
|
|
5
|
+
License-File: LICENSE.md
|
|
6
|
+
Author: Taylor B.
|
|
7
|
+
Author-email: tayjaybabee@gmail.com
|
|
8
|
+
Requires-Python: >=3.12,<4.0
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
16
|
+
Classifier: Topic :: Utilities
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: inspy-logger (==3.2.3)
|
|
19
|
+
Requires-Dist: inspyre-toolbox (>=1.5.3,<2.0.0)
|
|
20
|
+
Requires-Dist: pytz (>=2025.1,<2026.0)
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# easy-exit-calls
|
|
24
|
+
|
|
25
|
+
A Python library for managing exit handlers with enhanced features like decorators, UUID tracking, and LIFO execution.
|
|
26
|
+
|
|
27
|
+
## Features
|
|
28
|
+
|
|
29
|
+
- **Decorator Support**: Easily register functions as exit handlers using a decorator.
|
|
30
|
+
- **LIFO Execution**: Handlers execute in Last-In-First-Out order by default (configurable).
|
|
31
|
+
- **UUID Tracking**: Each handler is assigned a unique UUID for easy management.
|
|
32
|
+
- **Thread Safety**: Uses threading locks to ensure safe registration/unregistration.
|
|
33
|
+
- **Detailed Logging**: Integrated with a logging engine for debugging and tracking.
|
|
34
|
+
- **Error Handling**: Captures exceptions during exit and logs them with tracebacks.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
This project requires **Python 3.12** or later.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install easy-exit-calls
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
### Basic Decorator Usage
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from easy_exit_calls import register_exit_handler
|
|
50
|
+
|
|
51
|
+
@register_exit_handler
|
|
52
|
+
def cleanup():
|
|
53
|
+
print("Cleaning up resources...")
|
|
54
|
+
|
|
55
|
+
# Exiting the program will automatically trigger this handler.
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Decorator with Arguments
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from easy_exit_calls import register_exit_handler
|
|
62
|
+
|
|
63
|
+
@register_exit_handler("arg1", key="value")
|
|
64
|
+
def cleanup_with_args(arg1, key=None):
|
|
65
|
+
print(f"Cleaning up with {arg1} and {key}")
|
|
66
|
+
|
|
67
|
+
# Handler called with provided args/kwargs on exit.
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Manual Registration
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from easy_exit_calls import ExitCallHandler
|
|
74
|
+
|
|
75
|
+
def manual_cleanup():
|
|
76
|
+
print("Manual cleanup")
|
|
77
|
+
|
|
78
|
+
ExitCallHandler().register_handler(manual_cleanup)
|
|
79
|
+
|
|
80
|
+
# Exiting the program will manually trigger this handler.
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Unregistering Handlers
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from easy_exit_calls import ExitCallHandler
|
|
87
|
+
|
|
88
|
+
def cleanup():
|
|
89
|
+
print("Cleaning up resources...")
|
|
90
|
+
|
|
91
|
+
handler_uuid = ExitCallHandler().register_handler(cleanup)
|
|
92
|
+
|
|
93
|
+
# Unregister the handler by UUID.
|
|
94
|
+
ExitCallHandler().unregister_by_uuid(handler_uuid)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Execution Order
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from easy_exit_calls import register_exit_handler
|
|
101
|
+
|
|
102
|
+
@register_exit_handler
|
|
103
|
+
def first_handler():
|
|
104
|
+
print("First handler")
|
|
105
|
+
|
|
106
|
+
@register_exit_handler
|
|
107
|
+
def second_handler():
|
|
108
|
+
print("Second handler")
|
|
109
|
+
|
|
110
|
+
# Output on exit:
|
|
111
|
+
# Second handler
|
|
112
|
+
# First handler
|
|
113
|
+
# (LIFO execution order)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## API Reference
|
|
117
|
+
|
|
118
|
+
### `ExitCallHandler`
|
|
119
|
+
|
|
120
|
+
Singleton class managing exit handlers.
|
|
121
|
+
|
|
122
|
+
#### Methods:
|
|
123
|
+
|
|
124
|
+
- `register_handler(func: Callable, *args, **kwargs) -> str`:
|
|
125
|
+
Register a new exit handler with optional args/kwargs. Returns the UUID of the handler.<br><br>
|
|
126
|
+
- `unregister_by_uuid(uuid)`:
|
|
127
|
+
Unregister a handler by UUID.<br><br>
|
|
128
|
+
- `unregister_handler(func, *args, **kwargs)`:
|
|
129
|
+
Unregister a handler by function reference and optional args/kwargs.<br><br>
|
|
130
|
+
- `call_handlers()`:
|
|
131
|
+
Manually call all registered handlers.<br><br>
|
|
132
|
+
|
|
133
|
+
### `register_exit_handler`
|
|
134
|
+
|
|
135
|
+
Decorator for registering a function as an exit handler.
|
|
136
|
+
|
|
137
|
+
#### Parameters:
|
|
138
|
+
|
|
139
|
+
- `*handler_args`:
|
|
140
|
+
Optional arguments to pass to the handler function.<br><br>
|
|
141
|
+
- `**handler_kwargs`:
|
|
142
|
+
Optional keyword arguments to pass to the handler function.<br><br>
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
## Running Tests
|
|
146
|
+
|
|
147
|
+
Run the test suite with `pytest` from the project root:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
pytest
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Contributing
|
|
154
|
+
|
|
155
|
+
Contributions are welcome! Here's how you can get started:
|
|
156
|
+
1) Fork the repository.<br><br>
|
|
157
|
+
2) Create a new branch (`git checkout -b feature-branch`).<br><br>
|
|
158
|
+
3) Make your changes.<br><br>
|
|
159
|
+
4) Commit your changes (`git commit -m 'Add feature'`).<br><br>
|
|
160
|
+
5) Push your changes to your fork (`git push origin feature-branch`).<br><br>
|
|
161
|
+
6) Create a pull request.<br><br>
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
This project is released under the [MIT License](LICENSE.md).
|
|
167
|
+
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# easy-exit-calls
|
|
2
|
+
|
|
3
|
+
A Python library for managing exit handlers with enhanced features like decorators, UUID tracking, and LIFO execution.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Decorator Support**: Easily register functions as exit handlers using a decorator.
|
|
8
|
+
- **LIFO Execution**: Handlers execute in Last-In-First-Out order by default (configurable).
|
|
9
|
+
- **UUID Tracking**: Each handler is assigned a unique UUID for easy management.
|
|
10
|
+
- **Thread Safety**: Uses threading locks to ensure safe registration/unregistration.
|
|
11
|
+
- **Detailed Logging**: Integrated with a logging engine for debugging and tracking.
|
|
12
|
+
- **Error Handling**: Captures exceptions during exit and logs them with tracebacks.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
This project requires **Python 3.12** or later.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install easy-exit-calls
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
### Basic Decorator Usage
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from easy_exit_calls import register_exit_handler
|
|
28
|
+
|
|
29
|
+
@register_exit_handler
|
|
30
|
+
def cleanup():
|
|
31
|
+
print("Cleaning up resources...")
|
|
32
|
+
|
|
33
|
+
# Exiting the program will automatically trigger this handler.
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Decorator with Arguments
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from easy_exit_calls import register_exit_handler
|
|
40
|
+
|
|
41
|
+
@register_exit_handler("arg1", key="value")
|
|
42
|
+
def cleanup_with_args(arg1, key=None):
|
|
43
|
+
print(f"Cleaning up with {arg1} and {key}")
|
|
44
|
+
|
|
45
|
+
# Handler called with provided args/kwargs on exit.
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Manual Registration
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from easy_exit_calls import ExitCallHandler
|
|
52
|
+
|
|
53
|
+
def manual_cleanup():
|
|
54
|
+
print("Manual cleanup")
|
|
55
|
+
|
|
56
|
+
ExitCallHandler().register_handler(manual_cleanup)
|
|
57
|
+
|
|
58
|
+
# Exiting the program will manually trigger this handler.
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Unregistering Handlers
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from easy_exit_calls import ExitCallHandler
|
|
65
|
+
|
|
66
|
+
def cleanup():
|
|
67
|
+
print("Cleaning up resources...")
|
|
68
|
+
|
|
69
|
+
handler_uuid = ExitCallHandler().register_handler(cleanup)
|
|
70
|
+
|
|
71
|
+
# Unregister the handler by UUID.
|
|
72
|
+
ExitCallHandler().unregister_by_uuid(handler_uuid)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Execution Order
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from easy_exit_calls import register_exit_handler
|
|
79
|
+
|
|
80
|
+
@register_exit_handler
|
|
81
|
+
def first_handler():
|
|
82
|
+
print("First handler")
|
|
83
|
+
|
|
84
|
+
@register_exit_handler
|
|
85
|
+
def second_handler():
|
|
86
|
+
print("Second handler")
|
|
87
|
+
|
|
88
|
+
# Output on exit:
|
|
89
|
+
# Second handler
|
|
90
|
+
# First handler
|
|
91
|
+
# (LIFO execution order)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## API Reference
|
|
95
|
+
|
|
96
|
+
### `ExitCallHandler`
|
|
97
|
+
|
|
98
|
+
Singleton class managing exit handlers.
|
|
99
|
+
|
|
100
|
+
#### Methods:
|
|
101
|
+
|
|
102
|
+
- `register_handler(func: Callable, *args, **kwargs) -> str`:
|
|
103
|
+
Register a new exit handler with optional args/kwargs. Returns the UUID of the handler.<br><br>
|
|
104
|
+
- `unregister_by_uuid(uuid)`:
|
|
105
|
+
Unregister a handler by UUID.<br><br>
|
|
106
|
+
- `unregister_handler(func, *args, **kwargs)`:
|
|
107
|
+
Unregister a handler by function reference and optional args/kwargs.<br><br>
|
|
108
|
+
- `call_handlers()`:
|
|
109
|
+
Manually call all registered handlers.<br><br>
|
|
110
|
+
|
|
111
|
+
### `register_exit_handler`
|
|
112
|
+
|
|
113
|
+
Decorator for registering a function as an exit handler.
|
|
114
|
+
|
|
115
|
+
#### Parameters:
|
|
116
|
+
|
|
117
|
+
- `*handler_args`:
|
|
118
|
+
Optional arguments to pass to the handler function.<br><br>
|
|
119
|
+
- `**handler_kwargs`:
|
|
120
|
+
Optional keyword arguments to pass to the handler function.<br><br>
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
## Running Tests
|
|
124
|
+
|
|
125
|
+
Run the test suite with `pytest` from the project root:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
pytest
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Contributing
|
|
132
|
+
|
|
133
|
+
Contributions are welcome! Here's how you can get started:
|
|
134
|
+
1) Fork the repository.<br><br>
|
|
135
|
+
2) Create a new branch (`git checkout -b feature-branch`).<br><br>
|
|
136
|
+
3) Make your changes.<br><br>
|
|
137
|
+
4) Commit your changes (`git commit -m 'Add feature'`).<br><br>
|
|
138
|
+
5) Push your changes to your fork (`git push origin feature-branch`).<br><br>
|
|
139
|
+
6) Create a pull request.<br><br>
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
This project is released under the [MIT License](LICENSE.md).
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module provides a simple way to register exit handlers for your Python applications.
|
|
3
|
+
|
|
4
|
+
The main class is ExitCallHandler, which is used to register and manage exit handlers.
|
|
5
|
+
|
|
6
|
+
Included is a decorator, register_exit_handler, which can be used to register an exit handler for a function. This is a
|
|
7
|
+
convenient way to register exit handlers for functions.
|
|
8
|
+
|
|
9
|
+
Example:
|
|
10
|
+
>>> from easy_exit_calls import register_exit_handler, ExitCallHandler
|
|
11
|
+
>>>
|
|
12
|
+
>>> @register_exit_handler()
|
|
13
|
+
... def my_exit_handler():
|
|
14
|
+
... print("Exiting...")
|
|
15
|
+
...
|
|
16
|
+
>>> # Create an instance of ExitCallHandler
|
|
17
|
+
>>> eh = ExitCallHandler()
|
|
18
|
+
>>>
|
|
19
|
+
>>> # Register an exit handler
|
|
20
|
+
>>> eh.register_handler(my_exit_handler)
|
|
21
|
+
>>>
|
|
22
|
+
>>> # Call the exit handlers
|
|
23
|
+
>>> eh.call_handlers()
|
|
24
|
+
Exiting...
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from easy_exit_calls.classes import ExitCallHandler
|
|
28
|
+
from easy_exit_calls.decorator import register_exit_handler
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
'ExitCallHandler',
|
|
32
|
+
'register_exit_handler',
|
|
33
|
+
]
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import atexit
|
|
2
|
+
import threading
|
|
3
|
+
import traceback
|
|
4
|
+
from uuid import uuid4, UUID
|
|
5
|
+
from easy_exit_calls.log_engine import ROOT_LOGGER, Loggable
|
|
6
|
+
from easy_exit_calls.helpers.handler_list import HandlerList
|
|
7
|
+
|
|
8
|
+
MOD_LOGGER = ROOT_LOGGER.get_child('components.exit_calls')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ExitCallHandler(Loggable):
|
|
12
|
+
"""
|
|
13
|
+
A singleton class for managing exit handlers that are executed when the program terminates.
|
|
14
|
+
|
|
15
|
+
This class allows registration, execution, and removal of exit handlers. Handlers can be executed in
|
|
16
|
+
**either** LIFO (Last-In-First-Out) or FIFO (First-In-First-Out) order. It integrates with Python's `atexit`
|
|
17
|
+
module to ensure handlers are executed upon normal program termination.
|
|
18
|
+
|
|
19
|
+
Properties:
|
|
20
|
+
fifo (bool):
|
|
21
|
+
If True, handlers execute in FIFO order; otherwise, LIFO.
|
|
22
|
+
|
|
23
|
+
handler_keys (list):
|
|
24
|
+
A list of unique keys representing registered handlers.
|
|
25
|
+
|
|
26
|
+
handlers (list):
|
|
27
|
+
A list of registered handlers.
|
|
28
|
+
|
|
29
|
+
handler_uuids (list):
|
|
30
|
+
A list of UUIDs for registered handlers.
|
|
31
|
+
|
|
32
|
+
lifo (bool):
|
|
33
|
+
Indicates whether handlers execute in LIFO order.
|
|
34
|
+
|
|
35
|
+
registered_with_atexit (bool):
|
|
36
|
+
Indicates whether the handler is registered with `atexit`.
|
|
37
|
+
|
|
38
|
+
Methods:
|
|
39
|
+
call_handlers():
|
|
40
|
+
Executes all registered exit handlers.
|
|
41
|
+
|
|
42
|
+
clear_handlers():
|
|
43
|
+
Removes all registered exit handlers.
|
|
44
|
+
|
|
45
|
+
find_handler_by_uuid(uuid):
|
|
46
|
+
Retrieves a handler by its UUID.
|
|
47
|
+
|
|
48
|
+
function_registered(func):
|
|
49
|
+
Checks if a function is already registered as an exit handler.
|
|
50
|
+
|
|
51
|
+
has_key(key):
|
|
52
|
+
Determines if a handler with a given key exists.
|
|
53
|
+
|
|
54
|
+
has_uuid(uuid):
|
|
55
|
+
Determines if a handler with a given UUID exists.
|
|
56
|
+
|
|
57
|
+
register_handler(func, *args, return_func=False, **kwargs):
|
|
58
|
+
Registers a function as an exit handler.
|
|
59
|
+
|
|
60
|
+
register_self_with_atexit():
|
|
61
|
+
Registers the handler with Python’s `atexit` module.
|
|
62
|
+
|
|
63
|
+
unregister_all():
|
|
64
|
+
Unregisters all exit handlers.
|
|
65
|
+
|
|
66
|
+
unregister_all_with_name(name):
|
|
67
|
+
Unregisters all handlers with a specific name.
|
|
68
|
+
|
|
69
|
+
unregister_by_uuid(uuid):
|
|
70
|
+
Removes a registered handler by UUID.
|
|
71
|
+
|
|
72
|
+
unregister_handler(func, *args, **kwargs):
|
|
73
|
+
Unregisters a specific exit handler by function reference and arguments.
|
|
74
|
+
|
|
75
|
+
unregister_self_with_atexit():
|
|
76
|
+
Removes this handler from Python’s `atexit` module.
|
|
77
|
+
|
|
78
|
+
Example Usage:
|
|
79
|
+
```python
|
|
80
|
+
handler = ExitCallHandler()
|
|
81
|
+
|
|
82
|
+
def cleanup():
|
|
83
|
+
print("Cleaning up!")
|
|
84
|
+
|
|
85
|
+
handler.register_handler(cleanup)
|
|
86
|
+
```
|
|
87
|
+
"""
|
|
88
|
+
_instance = None
|
|
89
|
+
|
|
90
|
+
def __new__(cls, *args, **kwargs):
|
|
91
|
+
if cls._instance is None:
|
|
92
|
+
cls._instance = super(ExitCallHandler, cls).__new__(cls, *args, **kwargs)
|
|
93
|
+
# Use a list to store handler dictionaries
|
|
94
|
+
cls._instance._handlers = HandlerList(
|
|
95
|
+
on_empty=cls._instance.unregister_self_with_atexit,
|
|
96
|
+
on_non_empty=cls._instance.register_self_with_atexit
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
cls._instance._lifo = True
|
|
100
|
+
cls._instance._lock = threading.Lock()
|
|
101
|
+
|
|
102
|
+
return cls._instance
|
|
103
|
+
|
|
104
|
+
def __init__(self, fifo=False):
|
|
105
|
+
|
|
106
|
+
self.__registered_with_atexit = False
|
|
107
|
+
|
|
108
|
+
if isinstance(fifo, bool) and fifo:
|
|
109
|
+
self._lifo = False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
if not hasattr(self, '_initialized'):
|
|
113
|
+
super().__init__(MOD_LOGGER)
|
|
114
|
+
self._initialized = True
|
|
115
|
+
|
|
116
|
+
def _check_for_key(self, key):
|
|
117
|
+
"""
|
|
118
|
+
Checks if a key already exists in the registered handlers.
|
|
119
|
+
|
|
120
|
+
Parameters:
|
|
121
|
+
key (tuple):
|
|
122
|
+
A tuple containing the function, arguments, and keyword arguments of the handler.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
bool:
|
|
126
|
+
True if the key exists, False otherwise.
|
|
127
|
+
"""
|
|
128
|
+
for entry in self.handlers:
|
|
129
|
+
existing_key = self._get_key(entry['func'], entry['args'], entry['kwargs'])
|
|
130
|
+
if existing_key == key:
|
|
131
|
+
return True
|
|
132
|
+
|
|
133
|
+
def _cleanup(self):
|
|
134
|
+
"""
|
|
135
|
+
Executes all registered exit handlers.
|
|
136
|
+
"""
|
|
137
|
+
log = self.method_logger
|
|
138
|
+
|
|
139
|
+
handlers = reversed(self._handlers) if self.lifo else self._handlers
|
|
140
|
+
|
|
141
|
+
for entry in list(handlers):
|
|
142
|
+
name = ''
|
|
143
|
+
if 'handler_info' in entry:
|
|
144
|
+
info = entry['handler_info']
|
|
145
|
+
# Build a name based on module and function name
|
|
146
|
+
name = f"{info.get('module', '')}."
|
|
147
|
+
if info.get('name'):
|
|
148
|
+
name += info['name']
|
|
149
|
+
else:
|
|
150
|
+
name = "Unknown"
|
|
151
|
+
|
|
152
|
+
log.debug(f"Running exit handler {name}")
|
|
153
|
+
|
|
154
|
+
func = entry['func']
|
|
155
|
+
args = entry['args']
|
|
156
|
+
kwargs = entry['kwargs']
|
|
157
|
+
|
|
158
|
+
log.debug(f"Running exit handler {name} | Function: {func} | Args: {args} | Kwargs: {kwargs}")
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
func(*args, **kwargs)
|
|
162
|
+
except Exception as e:
|
|
163
|
+
log.error(f"Error while running exit handler {func}: {e}")
|
|
164
|
+
log.debug(f"Traceback:\n{traceback.format_exc()}")
|
|
165
|
+
raise e from e
|
|
166
|
+
|
|
167
|
+
def _get_key(self, func: callable, args: tuple, kwargs: dict):
|
|
168
|
+
"""
|
|
169
|
+
Create a unique key from a function, its arguments, and keyword arguments.
|
|
170
|
+
|
|
171
|
+
Parameters:
|
|
172
|
+
func (callable):
|
|
173
|
+
The function to be called.
|
|
174
|
+
|
|
175
|
+
args (tuple):
|
|
176
|
+
Positional arguments to be passed to the function.
|
|
177
|
+
|
|
178
|
+
kwargs (dict):
|
|
179
|
+
Keyword arguments to be passed to the function.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
tuple:
|
|
183
|
+
A tuple containing the function, arguments, and keyword arguments.
|
|
184
|
+
"""
|
|
185
|
+
return (func, args, frozenset(kwargs.items()))
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def fifo(self) -> bool:
|
|
189
|
+
"""
|
|
190
|
+
Get the FIFO mode for the handler.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
bool:
|
|
194
|
+
True if FIFO mode is enabled, False otherwise.
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
return not self._lifo
|
|
198
|
+
|
|
199
|
+
@fifo.setter
|
|
200
|
+
def fifo(self, new: bool) -> None:
|
|
201
|
+
"""
|
|
202
|
+
Set the FIFO mode for the handler.
|
|
203
|
+
|
|
204
|
+
Parameters:
|
|
205
|
+
new (bool):
|
|
206
|
+
True to set FIFO mode, False to set LIFO mode.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
None
|
|
210
|
+
|
|
211
|
+
Raises:
|
|
212
|
+
TypeError:
|
|
213
|
+
If the new value is not a boolean.
|
|
214
|
+
"""
|
|
215
|
+
if not isinstance(new, bool):
|
|
216
|
+
raise TypeError("fifo must be a boolean")
|
|
217
|
+
|
|
218
|
+
self._lifo = not new
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def handler_keys(self) -> list[tuple]:
|
|
222
|
+
"""
|
|
223
|
+
Returns a list of tuples containing the keys for all registered handlers.
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
list[tuple]:
|
|
227
|
+
A list of tuples containing the keys for all registered handlers;
|
|
228
|
+
each tuple contains the function, arguments, and keyword arguments.
|
|
229
|
+
"""
|
|
230
|
+
return [self._get_key(entry['func'], entry['args'], entry['kwargs']) for entry in self.handlers]
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def handlers(self) -> HandlerList:
|
|
234
|
+
"""
|
|
235
|
+
Returns a list of dictionaries representing the registered exit handlers.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
HandlerList:
|
|
239
|
+
A list of dictionaries representing the registered exit handlers.
|
|
240
|
+
"""
|
|
241
|
+
return self._handlers
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def handler_uuids(self) -> list[UUID]:
|
|
245
|
+
"""
|
|
246
|
+
Returns a list of UUIDs for all registered handlers.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
list[UUID]:
|
|
250
|
+
A list of UUIDs for all registered handlers.
|
|
251
|
+
"""
|
|
252
|
+
return [entry.get('uuid') for entry in self.handlers]
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def lifo(self):
|
|
256
|
+
"""
|
|
257
|
+
Get the LIFO status of the exit call handler.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
bool: True if the exit call handler is in LIFO mode, False otherwise.
|
|
261
|
+
"""
|
|
262
|
+
return self._lifo
|
|
263
|
+
|
|
264
|
+
@lifo.setter
|
|
265
|
+
def lifo(self, new) -> None:
|
|
266
|
+
"""
|
|
267
|
+
Set the LIFO status of the exit call handler.
|
|
268
|
+
|
|
269
|
+
If the value is True, handlers will execute in LIFO order. If False, handlers will execute in FIFO order.
|
|
270
|
+
|
|
271
|
+
Parameters:
|
|
272
|
+
new (bool):
|
|
273
|
+
The new LIFO status to set.
|
|
274
|
+
|
|
275
|
+
Returns:
|
|
276
|
+
None
|
|
277
|
+
"""
|
|
278
|
+
if not isinstance(new,bool):
|
|
279
|
+
raise ValueError("lifo must be a boolean")
|
|
280
|
+
|
|
281
|
+
self._lifo = new
|
|
282
|
+
|
|
283
|
+
@property
|
|
284
|
+
def registered_with_atexit(self) -> bool:
|
|
285
|
+
"""
|
|
286
|
+
Indicates whether the handler is registered with the `atexit` module.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
bool:
|
|
290
|
+
True if the handler is registered with `atexit`, False otherwise.
|
|
291
|
+
"""
|
|
292
|
+
return self.__registered_with_atexit
|
|
293
|
+
|
|
294
|
+
def call_handlers(self) -> None:
|
|
295
|
+
"""
|
|
296
|
+
Calls all registered exit handlers.
|
|
297
|
+
|
|
298
|
+
Returns:
|
|
299
|
+
None
|
|
300
|
+
"""
|
|
301
|
+
log = self.method_logger
|
|
302
|
+
|
|
303
|
+
if not self.handlers:
|
|
304
|
+
log.warning("No exit handlers registered")
|
|
305
|
+
return
|
|
306
|
+
|
|
307
|
+
log.debug("Calling exit handlers")
|
|
308
|
+
self._cleanup()
|
|
309
|
+
|
|
310
|
+
def clear_handlers(self) -> None:
|
|
311
|
+
"""
|
|
312
|
+
Removes all registered exit handlers.
|
|
313
|
+
|
|
314
|
+
Note:
|
|
315
|
+
Once all handlers are removed, the handler unregisters itself from the `atexit` module.
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
None
|
|
319
|
+
"""
|
|
320
|
+
log = self.method_logger
|
|
321
|
+
|
|
322
|
+
log.debug("Clearing all exit handlers")
|
|
323
|
+
self._handlers.clear()
|
|
324
|
+
log.debug("All exit handlers cleared")
|
|
325
|
+
|
|
326
|
+
def find_handler_by_uuid(self, uuid):
|
|
327
|
+
log = self.method_logger
|
|
328
|
+
|
|
329
|
+
if not isinstance(uuid, (UUID, str)):
|
|
330
|
+
log.error("UUID must be a UUID object or a string")
|
|
331
|
+
raise ValueError("UUID must be a UUID object or a string")
|
|
332
|
+
|
|
333
|
+
if isinstance(uuid, str):
|
|
334
|
+
uuid = UUID(uuid)
|
|
335
|
+
|
|
336
|
+
for entry in self.handlers:
|
|
337
|
+
if entry.get('uuid') and entry['uuid'] == uuid:
|
|
338
|
+
return entry
|
|
339
|
+
|
|
340
|
+
def function_registered(self, func):
|
|
341
|
+
return any([entry['func'] == func for entry in self.handlers])
|
|
342
|
+
|
|
343
|
+
def has_key(self, key):
|
|
344
|
+
return key in self.handler_keys
|
|
345
|
+
|
|
346
|
+
def has_uuid(self, uuid):
|
|
347
|
+
return any([entry.get('uuid') == uuid for entry in self.handlers])
|
|
348
|
+
|
|
349
|
+
def register_handler(self, func, *args, return_func=False, **kwargs):
|
|
350
|
+
log = self.method_logger
|
|
351
|
+
|
|
352
|
+
log.debug(f"Registering exit handler {func} | Args: {args} | Kwargs: {kwargs}")
|
|
353
|
+
|
|
354
|
+
# Check if the function is already registered
|
|
355
|
+
log.debug(f"Checking if handler {func} is already registered")
|
|
356
|
+
|
|
357
|
+
# Create a unique key from the function, its args, and kwargs
|
|
358
|
+
new_key = self._get_key(func, args, kwargs)
|
|
359
|
+
|
|
360
|
+
log.debug(f"New key: {new_key}")
|
|
361
|
+
|
|
362
|
+
if self.has_key(new_key):
|
|
363
|
+
log.warning(f"Handler {func} is already registered")
|
|
364
|
+
return func
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
info = {
|
|
368
|
+
'handler_info': {
|
|
369
|
+
'module': func.__module__,
|
|
370
|
+
'name': func.__name__,
|
|
371
|
+
},
|
|
372
|
+
'func': func,
|
|
373
|
+
'args': args,
|
|
374
|
+
'kwargs': kwargs,
|
|
375
|
+
'uuid': uuid4()
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
with self._lock:
|
|
379
|
+
# Otherwise, add the handler
|
|
380
|
+
self.handlers.append(info)
|
|
381
|
+
log.debug(f"Handler {func} registered successfully")
|
|
382
|
+
|
|
383
|
+
return info['uuid']
|
|
384
|
+
|
|
385
|
+
def register_self_with_atexit(self):
|
|
386
|
+
log = self.method_logger
|
|
387
|
+
|
|
388
|
+
log.debug('Checking if registered with atexit already...')
|
|
389
|
+
|
|
390
|
+
if not self.registered_with_atexit:
|
|
391
|
+
log.debug('Registering with atexit...')
|
|
392
|
+
atexit.register(self._cleanup)
|
|
393
|
+
self.__registered_with_atexit = True
|
|
394
|
+
|
|
395
|
+
def unregister_all(self):
|
|
396
|
+
self.clear_handlers()
|
|
397
|
+
|
|
398
|
+
def unregister_all_with_name(self, name: str) -> None:
|
|
399
|
+
"""
|
|
400
|
+
Unregister all exit handlers with a specific name.
|
|
401
|
+
|
|
402
|
+
Parameters:
|
|
403
|
+
name (str):
|
|
404
|
+
The name of the exit handlers to unregister.
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
None
|
|
408
|
+
"""
|
|
409
|
+
log = self.method_logger
|
|
410
|
+
|
|
411
|
+
log.debug(f"Unregistering all exit handlers with name {name}")
|
|
412
|
+
|
|
413
|
+
to_remove = []
|
|
414
|
+
for entry in list(self._handlers):
|
|
415
|
+
info = entry.get('handler_info', {})
|
|
416
|
+
if info.get('name') == name:
|
|
417
|
+
log.debug(
|
|
418
|
+
f"Removing handler {info.get('module', '')}.{info.get('name')}"
|
|
419
|
+
)
|
|
420
|
+
to_remove.append(entry)
|
|
421
|
+
|
|
422
|
+
for entry in to_remove:
|
|
423
|
+
self._handlers.remove(entry)
|
|
424
|
+
|
|
425
|
+
log.debug(f"All handlers with name {name} unregistered successfully")
|
|
426
|
+
|
|
427
|
+
def unregister_by_uuid(self, uuid):
|
|
428
|
+
log = self.method_logger
|
|
429
|
+
|
|
430
|
+
log.debug(f"Unregistering exit handler with UUID {uuid}")
|
|
431
|
+
|
|
432
|
+
handler = self.find_handler_by_uuid(uuid)
|
|
433
|
+
|
|
434
|
+
if handler:
|
|
435
|
+
log.debug(f"Removing handler {handler['func']}")
|
|
436
|
+
self._handlers.remove(handler)
|
|
437
|
+
log.debug(f"Handler with UUID {uuid} unregistered successfully")
|
|
438
|
+
return True
|
|
439
|
+
|
|
440
|
+
log.warning(f"Handler with UUID {uuid} not found")
|
|
441
|
+
|
|
442
|
+
return False
|
|
443
|
+
|
|
444
|
+
def unregister_handler(self, func, *args, **kwargs):
|
|
445
|
+
log = self.method_logger
|
|
446
|
+
|
|
447
|
+
log.debug(f"Unregistering exit handler {func} | Args: {args} | Kwargs: {kwargs}")
|
|
448
|
+
|
|
449
|
+
# Create a unique key from the function, its args, and kwargs
|
|
450
|
+
key = (func, args, frozenset(kwargs.items()))
|
|
451
|
+
|
|
452
|
+
log.debug(f"Key: {key}")
|
|
453
|
+
|
|
454
|
+
for entry in self._handlers:
|
|
455
|
+
existing_key = (entry['func'], entry['args'], frozenset(entry['kwargs'].items()))
|
|
456
|
+
if existing_key == key:
|
|
457
|
+
log.debug(f"Removing handler {func}")
|
|
458
|
+
self._handlers.remove(entry)
|
|
459
|
+
log.debug(f"Handler {func} unregistered successfully")
|
|
460
|
+
return func
|
|
461
|
+
|
|
462
|
+
log.warning(f"Handler {func} not found")
|
|
463
|
+
return None
|
|
464
|
+
|
|
465
|
+
def unregister_self_with_atexit(self):
|
|
466
|
+
log = self.method_logger
|
|
467
|
+
|
|
468
|
+
log.debug('Checking if registered with atexit already...')
|
|
469
|
+
|
|
470
|
+
if self.registered_with_atexit:
|
|
471
|
+
log.debug('Unregistering with atexit...')
|
|
472
|
+
atexit.unregister(self._cleanup)
|
|
473
|
+
self.__registered_with_atexit = False
|
|
474
|
+
return True
|
|
475
|
+
else:
|
|
476
|
+
log.warning('ExitCallHandler is not registered with atexit!')
|
|
477
|
+
|
|
478
|
+
return False
|
|
479
|
+
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"contributor": {
|
|
3
|
+
"preferred_name": "Example S. Developer",
|
|
4
|
+
"email_addresses": [
|
|
5
|
+
{
|
|
6
|
+
"user_handle": "example.s.developer",
|
|
7
|
+
"domain": "example.com"
|
|
8
|
+
}
|
|
9
|
+
],
|
|
10
|
+
"code_social": {
|
|
11
|
+
"github": [
|
|
12
|
+
{
|
|
13
|
+
"user_handle": "example_coder",
|
|
14
|
+
"on_behalf_of": [
|
|
15
|
+
{
|
|
16
|
+
"group_name": "Software Developer Inc.",
|
|
17
|
+
"group_handle": "software_developer_inc"
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
],
|
|
22
|
+
"gitlab": [
|
|
23
|
+
{
|
|
24
|
+
"user_handle": "example_dev",
|
|
25
|
+
"on_behalf_of": []
|
|
26
|
+
}
|
|
27
|
+
],
|
|
28
|
+
"bitbucket": [
|
|
29
|
+
{
|
|
30
|
+
"user_handle": "example_bb",
|
|
31
|
+
"on_behalf_of": []
|
|
32
|
+
}
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
"roles": [
|
|
36
|
+
"Developer",
|
|
37
|
+
"Maintainer",
|
|
38
|
+
"Contributor"
|
|
39
|
+
],
|
|
40
|
+
"contributions": {
|
|
41
|
+
"code": true,
|
|
42
|
+
"documentation": true,
|
|
43
|
+
"design": false,
|
|
44
|
+
"testing": true,
|
|
45
|
+
"bug_reports": true,
|
|
46
|
+
"community_support": false
|
|
47
|
+
},
|
|
48
|
+
"preferred_contact_method": "email",
|
|
49
|
+
"timezone": "America/Chicago",
|
|
50
|
+
"additional_notes": "Happy to contribute to open-source projects!"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from inspyre_toolbox.ver_man import PyPiVersionInfo, VersionParser
|
|
2
|
+
from inspyre_toolbox.ver_man.helpers import read_version_file
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
CWD = Path(__file__).parent
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
VERSION_FILE_PATH = CWD / '__VERSION__'
|
|
10
|
+
|
|
11
|
+
VERSION_PARSER = VersionParser(read_version_file(VERSION_FILE_PATH))
|
|
12
|
+
|
|
13
|
+
VERSION = VERSION_PARSER.version_str
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module contains the decorator function to register an exit handler with the ExitCallHandler.
|
|
3
|
+
|
|
4
|
+
The decorator function is register_exit_handler, which can be used to register an exit handler for a function. This is a
|
|
5
|
+
convenient way to register exit handlers for functions.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from easy_exit_calls import register_exit_handler
|
|
9
|
+
>>>
|
|
10
|
+
>>> @register_exit_handler()
|
|
11
|
+
... def my_exit_handler():
|
|
12
|
+
... print("Exiting...")
|
|
13
|
+
...
|
|
14
|
+
>>> # Call the exit handlers
|
|
15
|
+
>>> # Press Ctrl+D
|
|
16
|
+
Exiting...
|
|
17
|
+
|
|
18
|
+
Since:
|
|
19
|
+
1.0.0
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def register_exit_handler(*args, **kwargs):
|
|
24
|
+
"""
|
|
25
|
+
Register an exit handler with the ExitCallHandler.
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
*handler_args:
|
|
29
|
+
Positional arguments to pass to the handler function.
|
|
30
|
+
|
|
31
|
+
**handler_kwargs:
|
|
32
|
+
Keyword arguments to pass to the handler function.
|
|
33
|
+
"""
|
|
34
|
+
from easy_exit_calls import ExitCallHandler
|
|
35
|
+
|
|
36
|
+
# Case 1: Decorator used without parentheses (@register_exit_handler)
|
|
37
|
+
if len(args) == 1 and callable(args[0]):
|
|
38
|
+
func = args[0] # Get the function being decorated
|
|
39
|
+
ExitCallHandler().register_handler(func) # Register with no arguments
|
|
40
|
+
return func
|
|
41
|
+
|
|
42
|
+
# Case 2: Decorator used with arguments (@register_exit_handler(*args, **kwargs))
|
|
43
|
+
def decorator(func):
|
|
44
|
+
ExitCallHandler().register_handler(func, *args, **kwargs)
|
|
45
|
+
return func
|
|
46
|
+
|
|
47
|
+
return decorator
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = ['register_exit_handler']
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from os import system
|
|
2
|
+
from os import name
|
|
3
|
+
import time
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def clear_screen() -> None:
|
|
8
|
+
"""
|
|
9
|
+
Clear the screen.
|
|
10
|
+
|
|
11
|
+
This function will clear the screen of the terminal or command prompt. It will use the 'cls' command on Windows and
|
|
12
|
+
the 'clear' command on Unix-based systems.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
None
|
|
16
|
+
"""
|
|
17
|
+
if name == 'nt':
|
|
18
|
+
system('cls')
|
|
19
|
+
else:
|
|
20
|
+
system('clear')
|
|
21
|
+
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Create a function that can print 'Exiting...' to the screen where the ellipsis is animated.
|
|
26
|
+
def print_exit_message(
|
|
27
|
+
max_dots: int = 3,
|
|
28
|
+
interval: float = 0.5,
|
|
29
|
+
run_time: float = 5.0,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""
|
|
32
|
+
Print an animated 'Exiting...' message to the screen.
|
|
33
|
+
|
|
34
|
+
This function will print the message 'Exiting...' to the screen with an animated ellipsis. The ellipsis will
|
|
35
|
+
animate by adding a period to the end of the message every 0.5 seconds. The message will be printed to the screen
|
|
36
|
+
until the function is interrupted by the user.
|
|
37
|
+
|
|
38
|
+
Parameters:
|
|
39
|
+
max_dots:
|
|
40
|
+
The maximum number of dots to display in the animated ellipsis. Defaults to 3.
|
|
41
|
+
|
|
42
|
+
interval:
|
|
43
|
+
The interval between each dot addition in seconds. Defaults to 0.5.
|
|
44
|
+
|
|
45
|
+
run_time:
|
|
46
|
+
The maximum amount of time to run the function in seconds. Defaults to 5.0.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
None
|
|
50
|
+
"""
|
|
51
|
+
start_time = time.time()
|
|
52
|
+
dots = 0
|
|
53
|
+
while time.time() - start_time < run_time:
|
|
54
|
+
# Cycle through 1 to max_dots dots.
|
|
55
|
+
dots = (dots % max_dots) + 1
|
|
56
|
+
# Build the display string with padding to avoid leftover characters.
|
|
57
|
+
display_str = f'\rExiting{"." * dots}{" " * (max_dots - dots)}'
|
|
58
|
+
sys.stdout.write(display_str)
|
|
59
|
+
sys.stdout.flush()
|
|
60
|
+
time.sleep(interval)
|
|
61
|
+
# Final display to ensure the full ellipsis is visible.
|
|
62
|
+
sys.stdout.write(f'\rExiting{"." * max_dots}\n')
|
|
63
|
+
sys.stdout.flush()
|
|
64
|
+
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def simple_example_handler() -> None:
|
|
69
|
+
print_exit_message()
|
|
70
|
+
|
|
71
|
+
return
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module contains the decorator function to register an exit handler with the ExitCallHandler.
|
|
3
|
+
|
|
4
|
+
The decorator function is register_exit_handler, which can be used to register an exit handler for a function. This is a
|
|
5
|
+
convenient way to register exit handlers for functions.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from easy_exit_calls import register_exit_handler
|
|
9
|
+
>>>
|
|
10
|
+
>>> @register_exit_handler()
|
|
11
|
+
... def my_exit_handler():
|
|
12
|
+
... print("Exiting...")
|
|
13
|
+
...
|
|
14
|
+
>>> # Call the exit handlers
|
|
15
|
+
>>> # Press Ctrl+D
|
|
16
|
+
Exiting...
|
|
17
|
+
|
|
18
|
+
Since:
|
|
19
|
+
1.0.0
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def register_exit_handler(*args, **kwargs):
|
|
24
|
+
"""
|
|
25
|
+
Register an exit handler with the ExitCallHandler.
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
*handler_args:
|
|
29
|
+
Positional arguments to pass to the handler function.
|
|
30
|
+
|
|
31
|
+
**handler_kwargs:
|
|
32
|
+
Keyword arguments to pass to the handler function.
|
|
33
|
+
"""
|
|
34
|
+
from easy_exit_calls import ExitCallHandler
|
|
35
|
+
|
|
36
|
+
# Case 1: Decorator used without parentheses (@register_exit_handler)
|
|
37
|
+
if len(args) == 1 and callable(args[0]):
|
|
38
|
+
func = args[0] # Get the function being decorated
|
|
39
|
+
ExitCallHandler().register_handler(func) # Register with no arguments
|
|
40
|
+
return func
|
|
41
|
+
|
|
42
|
+
# Case 2: Decorator used with arguments (@register_exit_handler(*args, **kwargs))
|
|
43
|
+
def decorator(func):
|
|
44
|
+
ExitCallHandler().register_handler(func, *args, **kwargs)
|
|
45
|
+
return func
|
|
46
|
+
|
|
47
|
+
return decorator
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = ['register_exit_handler']
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from collections import UserList
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class HandlerList(UserList):
|
|
6
|
+
"""
|
|
7
|
+
A list-like object that triggers a callback when the list either becomes empty or non-empty.
|
|
8
|
+
"""
|
|
9
|
+
def __init__(self, *args, on_empty=None, on_non_empty=None):
|
|
10
|
+
super().__init__(*args)
|
|
11
|
+
self.__on_empty = on_empty if callable(on_empty) else None
|
|
12
|
+
self.__on_non_empty = on_non_empty if callable(on_non_empty) else None
|
|
13
|
+
self.__was_empty = not bool(self.data)
|
|
14
|
+
|
|
15
|
+
def _check_state(self) -> None:
|
|
16
|
+
"""
|
|
17
|
+
Check the current state of the list and trigger the appropriate callback.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
None
|
|
21
|
+
"""
|
|
22
|
+
is_empty = not bool(self.data)
|
|
23
|
+
|
|
24
|
+
if is_empty and not self.was_empty:
|
|
25
|
+
self.on_empty()
|
|
26
|
+
elif not is_empty and self.was_empty:
|
|
27
|
+
self.on_non_empty()
|
|
28
|
+
|
|
29
|
+
self.__was_empty = is_empty
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def on_empty(self) -> Optional[callable]:
|
|
33
|
+
return self.__on_empty
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def on_non_empty(self) -> Optional[callable]:
|
|
37
|
+
return self.__on_non_empty
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def was_empty(self) -> bool:
|
|
41
|
+
return self.__was_empty
|
|
42
|
+
|
|
43
|
+
def append(self, item) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Append an item to the list and check the state.
|
|
46
|
+
|
|
47
|
+
Parameters:
|
|
48
|
+
item:
|
|
49
|
+
The item to be appended.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
None
|
|
53
|
+
"""
|
|
54
|
+
super().append(item)
|
|
55
|
+
self._check_state()
|
|
56
|
+
|
|
57
|
+
def clear(self) -> None:
|
|
58
|
+
"""
|
|
59
|
+
Clear the list and check the state.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
None
|
|
63
|
+
"""
|
|
64
|
+
super().clear()
|
|
65
|
+
self._check_state()
|
|
66
|
+
|
|
67
|
+
def extend(self, other: list) -> None:
|
|
68
|
+
"""
|
|
69
|
+
Extend the list with another iterable and check the state.
|
|
70
|
+
|
|
71
|
+
Parameters:
|
|
72
|
+
other:
|
|
73
|
+
The iterable to extend the list with.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
None
|
|
77
|
+
"""
|
|
78
|
+
super().extend(other)
|
|
79
|
+
self._check_state()
|
|
80
|
+
|
|
81
|
+
def insert(self, index: int, item: any) -> None:
|
|
82
|
+
"""
|
|
83
|
+
Insert an item at the specified index and check the state.
|
|
84
|
+
|
|
85
|
+
Parameters:
|
|
86
|
+
index (int):
|
|
87
|
+
The index at which to insert the item.
|
|
88
|
+
item (any):
|
|
89
|
+
The item to be inserted.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
None
|
|
93
|
+
"""
|
|
94
|
+
super().insert(index, item)
|
|
95
|
+
self._check_state()
|
|
96
|
+
|
|
97
|
+
def pop(self, index: int = -1) -> any:
|
|
98
|
+
"""
|
|
99
|
+
Remove and return the item at the specified index and check the state.
|
|
100
|
+
|
|
101
|
+
Parameters:
|
|
102
|
+
index (int, optional):
|
|
103
|
+
The index of the item to be removed. Defaults to the last item.
|
|
104
|
+
"""
|
|
105
|
+
item = super().pop(index)
|
|
106
|
+
self._check_state()
|
|
107
|
+
|
|
108
|
+
return item
|
|
109
|
+
|
|
110
|
+
def remove(self, item: any) -> None:
|
|
111
|
+
"""
|
|
112
|
+
Remove the first occurrence of the specified item and check the state.
|
|
113
|
+
|
|
114
|
+
Parameters:
|
|
115
|
+
item (any):
|
|
116
|
+
The item to be removed.
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
None
|
|
120
|
+
"""
|
|
121
|
+
super().remove(item)
|
|
122
|
+
self._check_state()
|
|
123
|
+
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "easy-exit-calls"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "A Python library for managing exit handlers with enhanced features like decorators, UUID tracking, and LIFO execution."
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Taylor B.",email = "tayjaybabee@gmail.com"}
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.12,<4.0"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"inspyre-toolbox (>=1.5.3,<2.0.0)",
|
|
12
|
+
"inspy-logger (==3.2.3)",
|
|
13
|
+
"pytz (>=2025.1,<2026.0)"
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
23
|
+
"Topic :: Utilities",
|
|
24
|
+
"Typing :: Typed"
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[[tool.poetry.source]]
|
|
28
|
+
name = "test-pypi"
|
|
29
|
+
url = "https://test.pypi.org/simple/"
|
|
30
|
+
priority = "explicit"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
35
|
+
build-backend = "poetry.core.masonry.api"
|