How to reload Python module in IDLE?
I'm trying to understand how my workflow can work with Python and IDLE.
Suppose I write a function:
开发者_StackOverflowdef hello():
print 'hello!'
I save the file as greetings.py
. Then in IDLE, I test the function:
>>> from greetings import *
>>> hello()
hello!
Then I alter the program, and want to try hello()
again. So I reload
:
>>> reload(greetings)
<module 'greetings' from '/path/to/file/greetings.py'>
Yet the change is not picked up. What am I doing wrong? How do I reload an altered module?
I've been reading a number of related questions on SO, but none of the answers have helped me.
You need to redo this line:
>>> from greetings import *
after you do
>>> reload(greetings)
The reason just reloading the module doesn't work is because the * actually imported everything inside the module, so you have to reload those individually. If you did the following it would behave as you expect:
>>> import greetings
>>> greetings.hello()
hello!
Make change to file
>>> reload(greetings)
<module 'greetings' from 'greetings.py'>
>>> greetings.hello()
world!
Here's what I get when I try your example (from a fresh Python interactive session):
>>> from greetings import *
>>> reload(greetings)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'greetings' is not defined
This indicates the source of the problem. When you use from greetings import *
, the name greetings
is not imported into the global namespace. Therefore, you cannot use reload(greetings)
on it.
To fix this, try the following:
>>> import greetings
>>> greetings.hello()
hello
>>> reload(greetings)
<module 'greetings' from 'greetings.pyc'>
>>> greetings.hello()
hello world
IDLE has a menu pick to run the current file. This will restart the shell by running your file first, reloading it.
On windows, I use the shell->Restart shell or CTRL+F6 shortcut to restart and load the latest version of the modue
精彩评论