Performing an action as python script closes
<p>I was wondering if it was possible to perform an action at any given point in  a basic python script, so say when it is close. I have the following code to find prime numbers (Just for fun)</p>

<pre><code>number = 1
primelist = []
nonprime = []

while number &lt; 1000:

    number += 1

    for i in range(number):
        if i != 1 and i != number and i !=0:
            if number%i == 0:
                nonprime.append(number)
            else:
                primelist.append(number)

nonprimes = open("nonprimes.txt", "w")

for nonprime in set(primelist) &amp; set(nonprime):
    nonprimes.write(str(nonprime) + ", ")

nonprimes.close()
</code></pre>

<p>So basically i wanted to run the last part as the script is stopped. If this isn't possible is there a way where say i press "space" while the program is running and then it saves the list?</p>

<p>Cheers in advance :)</p>

<p>EDIT:</p>

<p>I've modified the code to include the atexit module as suggested, but it doesn't appear to be working. Here it is:</p>

<p>import time, atexit</p>

<pre><code>class primes():



    def __init__(self):

        self.work(1)

    def work(self, number):

        number = 1
        self.primelist = []
        self.nonprime = []

        while number &lt; 20:
            time.sleep(0.1)
            print "Done"

            number += 1

            for i in range(number):
                if i != 1 and i != number and i !=0:
                    if number%i == 0:
                        self.nonprime.append(number)
                    else:
                        self.primelist.append(number)

        nonprimes = open("nonprimes.txt", "w")

        for nonprime in set(self.primelist) &amp; set(self.nonprime):
            nonprimes.write(str(nonprime) + ", ")

        nonprimes.close()


    def exiting(self, primelist, nonprimelist):
        primelist = self.primelist
        nonprimelist = self.nonprime

        nonprimes = open("nonprimes.txt", "w")

        for nonprime in set(self.primelist) &amp; set(self.nonprime):
            nonprimes.write(str(nonprime) + ", ")

        nonprimes.close()

atexit.register(exiting)


if __name__ == "__main__":
    primes()
</code></pre>
