0

I have seen a very strange phenomenon. I use python3.3. When I try to start and kill my code several times, the consequences show differently.

The following is my code:

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

The following is what I have tried:
enter image description here

But if I add import os in __del__, then everything behaves well. Why does it shows that Exception AttributeError: "'NoneType' object has no attribute 'remove'" sometimes?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
flyer
  • 9,280
  • 11
  • 46
  • 62
  • Your module globals are being cleared up; `os` is set to `None` by the time the `__del__` handler is called. – Martijn Pieters Jun 15 '14 at 13:17
  • Also related: [Can a simple difference in Python3 variable names alter the way code runs?](http://stackoverflow.com/q/22864764) – Martijn Pieters Jun 15 '14 at 13:19
  • @MartijnPieters Thank you very much! Now I know it's the result of python3.3 setting all objects in `globals()` to `None` when the interpreter exits and the order of objects in `globals()` being random. – flyer Jun 15 '14 at 13:31

0 Answers0