Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atexit function executed at program start

Tags:

python

atexit

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.

like image 256
madprogramer Avatar asked Mar 02 '26 02:03

madprogramer


2 Answers

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().

like image 146
NPE Avatar answered Mar 04 '26 17:03

NPE


You are registering the return value of the function instead of the function itself. Instead of calling it before registering, just pass in the function reference:

atexit.register(save_f)
like image 42
Martijn Pieters Avatar answered Mar 04 '26 17:03

Martijn Pieters