SUCIALISM

Logo

Hello, my name is John Su. Welcome to my homepage. I'm a senior technical director, technical artist, game engineer, VFX artist, and art-lover.

View My GitHub Profile

6 December 2020

Handling Unhandled Exception In Python

by John

When reading the source code of rez-localz, I noticed that there’s a fancy way to do the clean up before exiting exceptionally.

def excepthook(type, value, traceback):
    """Clean up temporary files"""

    cleanup()
    sys.__excepthook__(type, value, traceback)

...

sys.excepthook = excepthook
atexit.register(cleanup)

So the cleanup would get called whenever except encountered or exit exceptionally.

Moreover, there’s a concise implementation to get the total size of a folder:

def dirsize(path):
    return sum(
        os.path.getsize(os.path.join(dirpath, filename))
        for dirpath, dirnames, filenames in os.walk(path)
        for filename in filenames
    )

That’s chill.

views: tags: python - archive