5

I am working on a program that needs to call a function right before exiting, and was successfully using atexit.register(myFunction) to do so, until it stopped working. Even when I try running just a simple script, the registered function is not being called...

Here is the simple code:

import atexit def all_done(): print ('all_done()') print ('Registering') atexit.register(all_done) print ('Registered') 

And the output is:

Registering Registered 

When it should be:

Registering Registered all_done() 

What could be the problem? Like I said, it was working for a while, then suddenly stopped.

4
  • I'm not able to reproduce your problem. I'm getting your expected output. Commented Mar 24, 2020 at 21:42
  • How do you run this code? Commented Mar 24, 2020 at 21:54
  • Like I said, it was working at one point. I get the sense that something must have messed up the module somehow, because I don't think anything is wrong with the code. Commented Mar 24, 2020 at 21:58
  • There isn't enough to go on, so a bit of a wild guess... the interpreter actually never terminates (i.e. you're using IDE that keeps the session alive)? The other options being, it gets terminated by a signal which is (can)not be handled and interpreter terminates without calling registered function? Commented Mar 24, 2020 at 22:17

2 Answers 2

6

Welcome, 2 year old post. In case you're having the same problem: keep in mind that, quote, "The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called."

That means things like a system shutdown or os._exit() won't call the atexit function, but things like a keyboard interrupt or sys.exit() will do no problem.

example:

import atexit def all_done(): print ('all_done()') print ('Registering') atexit.register(all_done) print ('Registered') os._exit() 

will output

Registering Registered 

But, this code here:

import atexit def all_done(): print ('all_done()') print ('Registering') atexit.register(all_done) print ('Registered') sys.exit() 

will output

Registering Registered all_done() 

Hope i was of help!

source: https://docs.python.org/3/library/atexit.html

Sign up to request clarification or add additional context in comments.

Comments

1

I ended up not using atexit, instead just

try: ... finally: ... 

which is now working. Still don't know why atexit doesn't work, though...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.