cleanups¶
Process exit cleanup registration and execution utilities.
This module provides a mechanism for registering cleanup functions that are automatically executed at process exit (via atexit) or on demand. Cleanups are stored in a global namespace variable so they survive across fork boundaries in multiprocessing scenarios.
Cleanups run in reverse registration order, and an exception raised by one cleanup does not stop the remaining ones from running.
Example
from py_misc_utils import cleanups
cleanups.register(lambda: print('cleaning'))
cleanups.run() # Also executed automatically at process exit.
register(fn, *args, **kwargs)
¶
Register a cleanup function on the global _Cleanups instance.
See _Cleanups.register() for details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
The callable to invoke during cleanup. |
required | |
*args
|
Positional arguments to pass to fn. |
()
|
|
**kwargs
|
Keyword arguments to pass to fn. |
{}
|
Returns:
| Type | Description |
|---|---|
|
An integer ID that can be used to unregister this cleanup later. |
Source code in py_misc_utils/cleanups.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
reg(fn)
¶
Decorator that registers a function as a cleanup and returns it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
The function to register as a cleanup. |
required |
Returns:
| Type | Description |
|---|---|
|
The same function object that was passed in. |
Source code in py_misc_utils/cleanups.py
149 150 151 152 153 154 155 156 157 158 159 160 | |
unregister(cid, run=False)
¶
Unregister a cleanup by ID on the global _Cleanups instance.
See _Cleanups.unregister() for details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cid
|
The integer ID returned by register(). |
required | |
run
|
If True, execute the cleanup before removing it. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
|
The removed _Cleaner namedtuple, or None if not found. |
Source code in py_misc_utils/cleanups.py
163 164 165 166 167 168 169 170 171 172 173 174 175 | |
run()
¶
Execute all registered cleanups on the global _Cleanups instance.
Delegates to _Cleanups.run().
Source code in py_misc_utils/cleanups.py
178 179 180 181 182 183 | |