Detect when macro execution ends?

Is there a way to detect when a macro is done executing.

I am working on oooscript.
It packs python libraries into a single file and compiles the result into a LibreOffice Document.
This is done to allow a multi file (python package) to be executed as a macro.

This is done in part by a special entry point file that loads the python lib location into the python sys.path.

It is not critical but I would like to remove the entry from the sys.path after the macro is done executing and add it again when the macro executes. Adding is easy. I don’t know how to detect when macro is done executing.

I know it is possible to implement some sort of callback or event when that can be triggered in each macro function but this is not a good choice. oooscript is meant to allow developers to have flexibility and require implementing callback is not a good option.

I was able to use a different approach. I published oooscript Version 2.0.0 which now has an option to compile in binary. This is much faster then the previous version.


Using a context manager that adds to the current sys.path I am able to import the code to run the macro and then the context manager removes the module path from sys.path

@contextmanager
def importer_file(module_path: Path | str):
    pth = str(Path(module_path))
    sys.path.insert(0, pth)
    try:
        yield
    finally:
        sys.path.remove(pth)


try:
    ipd = ImportDocPyz("___pyz___.pyz")
    ipd.set_pyz()
    if ipd.allow_print:
        print(f"extracted_path: {ipd.extracted_path}")
    with importer_file(ipd.extracted_path):
        from ___pyz___.__main__ import *
except Exception as e:
    print(f"Error: {e}")
    traceback.print_exc()

The source file can be found here.