Here is my code to reload a python module using the reload() build in function. I have looked at some (not all 🙂 ) the other questions and answers in stackoverflow but to get my code to work I still need to do a os.remove(‘m.pyc’). Can anybody maybe explain it to me or show me how I need to change my code to make the below work without the remove.
import os
open('m.py','wt').write(r'def f(str): print "Sooo Original : %s"%(str)')
import m
m.f('Original')
os.remove('m.pyc')
open('m.py','wt').write(r'def f(str): print "Not so original : %s"%(str)')
m = reload(m)
m.f('Copy')
By replacing your remove statement with
time.sleep(1)to prevent both files from being created nearly simultaneously, I obtain the correct result. I guess the problem is that both files have the same time stamp which prevents Python from detecting the change and truly reload the module.