Another Python module reload question
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.
I get a different problem on my machine.
Traceback (most recent call last):
File "test.py", line 8, in <module>
m.f('Original')
AttributeError: 'module' object has no attribute 'f'
I've noticed that you didn't close your file, so it may that the contents of the file are being held in a buffer and are waiting to be written to disk. So when you come to reloading the module, python still sees the original version of the file.
From the documentation for file.write
write(...) write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
Does the following work for you?
f = open('m.py','wt')
f.write(r'def f(str): print "Sooo Original : %s"%(str)')
f.close()
import m
m.f('Original')
f = open('m.py','wt')
f.write(r'def f(str): print "Not so original : %s"%(str)')
f.close()
m = reload(m)
m.f('Copy')
精彩评论