python-3.xatexit

How should i use atexit in python?


I use this code below but it only outputs a "TypeError: the first argument must be callable"

import atexit

def end_script():
    print("ahh yes it works")

atexit.register(end_script())

while True:
    print("It still doesn't work")

Shouldn't atexit.register(x) just call x when the script closes? All the reference I got is confusing so I'm kinda lost here.


Solution

  • You called end_script and passed its return value to register. Don't call it, just do:

    atexit.register(end_script)  # No call parens after end_script