[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Importing v reloading modules modules

Gabriel Genellina

3/20/2010 1:28:00 AM

En Fri, 19 Mar 2010 14:09:09 -0300, Peter Peyman Puk
<peter_peyman_puk@yahoo.ca> escribió:

> I am running a simulator written in python. The simulator has a small
> TextView (actually a SourceView) widget which lets the user writes
> scripts, and when they are satisfied they can execute that script to get
> results. For arguments sake, we write a simple script and save it as
> A.py and we import it and execute it more or less like so.
>
> import A
>
> #assume there is a function called test() in module A
> A.test()
>
>
> Then the user modifies the contents of A.py and saves it again (to A.py)
> now all we have to do is the following
>
> if 'A' in dir():
> reload(A)
> else:
> import A
>
> A.test()

Terry Reedy already gave you an answer for this import problem.
I'd like to go one step back and question whether using import/modules is
the right thing here.
Clearly A.py is not a module but a script (that's the word you used) - and
one does not *import* a script but *executes* it.
That is, instead of using import/__import__, use exec (or execfile) within
a known namespace:

import __builtin__
ns = {'__builtins__': __builtin__.__dict__}
exec contents_of_textview in ns
# any change made to ns is visible here

--
Gabriel Genellina