异常AttributeError:"' NoneType'对象没有属性'删除'"

时间:2014-06-15 13:15:25

标签: python python-3.x python-3.3

我看到一个非常奇怪的现象。我用的是python3.3。当我尝试多次启动并终止我的代码时,后果显示不同。

以下是我的代码:

import os
import sys
import time


class Test(object):

    def __init__(self, name):
        self.name = name

        # set file pid
        self.fname_pid = self._write_pid()

    def __del__(self):
        # import os
        os.remove(self.fname_pid)

    def _write_pid(self):
        dir_home = os.getenv('HOME')
        dir_pids = os.path.join(dir_home, 'pids')

        fname_pid = 'pid_{0}'.format(__file__.split('.')[0])
        fname_pid = os.path.join(dir_pids, fname_pid)

        with open(fname_pid, 'w') as fp_pid:
            fp_pid.write(str(os.getpid()))

        return fname_pid

    def run(self):
        while True:
            print(self.name)
            time.sleep(2)


if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.exit('Usage: $ python Test names')

    name = sys.argv[1]

    test = Test(name)

    try:
        test.run()
    except KeyboardInterrupt:
        print('Thank you for using.')

以下是我的尝试:
enter image description here

但如果我在import os中添加__del__,那么一切都表现良好。为什么会显示 Exception AttributeError:"' NoneType'对象没有属性'删除' 有时?

0 个答案:

没有答案