0

我想知道是否可以在基本 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()
4

2 回答 2

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"
于 2013-02-28T12:36:29.427 回答
0

虽然我很确定文件对象会在回收时进行清理并将内容刷新到文件中。解决这个问题的最好方法是使用 with 语句。

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

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

于 2013-02-28T12:19:05.133 回答