我試圖加載代碼的模塊,然後重新加載相同的模塊,但不同的代碼編程的Python:無法加載在Python正確的模塊,而無需刪除PYC文件
import imp
a = """
def test():
print "Hello from a"
"""
b = """
def test():
print "Hello from b"
"""
for code in [a, b]:
with open('user.py', 'wb') as f:
f.write(code)
mod = imp.load_source('user', 'user.py')
getattr(mod, "test")()
預期輸出:
Hello from a
Hello from b
實際輸出:
Hello from a
Hello from a
顯然,我的它是如何工作的理解是不t正確,但我似乎無法弄清楚我的錯誤。
只有在編寫文件f
中的代碼之前,我刪除了生成的.pyc文件,才能使其正常工作。有沒有更好的辦法?
參見http://stackoverflow.com/questions/6477528/another-python-module-reload-question。 – nneonneo