Search code examples
pythonatexit

Atexit function executed at program start


I have this simple procedure:

def save_f():
    global register
    register = register_registerer()
    outFile = open('FobbySave.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()
    print register

atexit.register(save_f())

The problem is that save_f gets called as soon as I run my program. This isn't all of my code, just the important part. If there is nothing wrong here please tell me, so that I know what to do.


Solution

  • Change

    atexit.register(save_f())
    

    to

    atexit.register(save_f)
    

    In your original code, the save_f() calls the function. The return value of the function (i.e. None) is then passed to atexit.register().

    The correct version passes the function object itself to atexit.register().