简体   繁体   中英

Alternative to python atexit module that works when called from other scripts

Using atexit.register(function) to register a function to be called when your python script exits is a common practice.

The problem is that I identified a case when this fails in an ugly way: if your script it executed from another python script using the execfile() .

In this case you will discover that Python will not be able to locate your function when it does exits, and this makes sense.

My question is how to keep this functionality in a way that does not presents this issue.

I think the problem you're having is with the location of the current working directory. You could ensure that you're specifying the correct location doing something like this:

import os

target = os.path.join(os.path.dirname(__file__), "mytarget.py")

This works for me. I created a file to be executed by another file, a.py :

$ cat a.py 
import atexit

@atexit.register
def myexit():
    print 'myexit in a.py'

And then b.py to call execfile:

$ cat b.py 
import atexit

@atexit.register
def b_myexit():
    print 'b_myexit in b.py'

execfile('a.py')

When I run b.py , both registered functions get called:

$ python b.py 
myexit in a.py
b_myexit in b.py

Note that both of these scripts are in the same directory when I ran them. If your a.py is in a separate directory as Ryan Ginstrom mentioned in his answer, you will need to use the full path to it, like:

execfile('/path/to/a.py')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM