关闭时执行python脚本操作

时间:2013-02-28 12:14:25

标签: python

我想知道是否可以在基本python脚本中的任何给定点执行操作,所以说当它关闭时。我有以下代码来查找素数(只是为了好玩)

number = 1
primelist = []
nonprime = []

while number < 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) & set(nonprime):
    nonprimes.write(str(nonprime) + ", ")

nonprimes.close()

所以基本上我想在脚本停止时运行最后一部分。如果这是不可能的,有没有办法说我在程序运行时按“空格”然后保存列表?

提前干杯:)

编辑:

我已修改代码以按照建议包含atexit模块,但它似乎不起作用。这是:

导入时间,atexit

class primes():



    def __init__(self):

        self.work(1)

    def work(self, number):

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

        while number < 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) & 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) & set(self.nonprime):
            nonprimes.write(str(nonprime) + ", ")

        nonprimes.close()

atexit.register(exiting)


if __name__ == "__main__":
    primes()

2 个答案:

答案 0 :(得分:0)

虽然我非常肯定文件对象会在回收时清理并刷新文件。解决这个问题的最佳方法是使用with语句。

with open("nonprimes.txt", "w") as nonprimes:
    for nonprime in set(primelist) & set(nonprime):
        nonprimes.write(str(nonprime) + ", ")

关闭文件的锅炉板代码等在语句结束时自动执行。

答案 1 :(得分:0)

Python有一个atexit模块,允许您注册脚本退出时要执行的代码:

import atexit, sys

def doSomethingAtExit():
    print "Doing something on exit"

atexit.register(doSomethingAtExit)

if __name__ == "__main__":
    sys.exit(1)
    print "This won't get called"