Reloading on the fly: was: Re: Python Productivity over C++

Hung Jung Lu hungjunglu at hotmail.com
Fri Jun 9 18:03:15 EDT 2000


--- In python-list at egroups.com, boud at r... (Boudewijn Rempt) wrote:
>Could you post an example of designing the main program to reload
>submodules? I'd like to get that working, too, and coming from
>languages where that's impossible, I've a bit of trouble coming up
>with a solution...

This is a very simple reloader, but it gives you an idea. Make two Python 
files names M1.py and M2.py:

M1.py
===============================================================
import sys
import thread
import time

def reloader():
    while 1:
        module_name = raw_input('module to reload: ')
        modules = sys.modules
        if modules.has_key(module_name):
            print 'reloading'
            reload(modules[module_name])
        else:
            print 'importing'
            exec 'import %s' % module_name
        time.sleep(1.0)

if __name__ == '__main__':
    thread.start_new_thread(reloader, ())
    while 1:
        time.sleep(1.0)

==================================================================

M2.py
=============================
print 'Hello World!'
=============================


Now, run the first file in a shell (or double click on it in Windows 
system), and then type in M2 at the prompt, then go to M2 and edit it by 
hand (change to something like print 'bye bye World'), and then type in M2 
again at the prompt. See the magic.

The thing is, if you modularize your huge python project into small modules, 
you can really achieve good reloading and that makes your debugging easier. 
This is especially true for large projects where the penalty of setting up 
the initial state is very time consuming (like when you are debugging a 
computer game module... there might be some error that happens only after 
you've played 27 dungeon rooms. Not that I have programmed games in Python, 
it's just an analogy.)

regards,

Hung Jung

________________________________________________________________________
Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com





More information about the Python-list mailing list