views:

27

answers:

2

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.

A: 

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")
Ryan Ginstrom
A: 

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')
bstpierre