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:
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?