[Tutor] Puzzled by execfile(): solved (?)

Liam Clarke cyresse at gmail.com
Thu Oct 21 03:27:41 CEST 2004


That makes my head hurt trying to follow that. What exactly are you
trying to do?
If it's doing what you want it to do, the code is fine.
There are myriad different ways you could reconstruct that, and they'd
all have the same effect.

My question is, can a module called with execfile return a value if it has the 
if __name__==main() thing?

My golden rule is "If it does what I want, it's fine."
My silver rule is "There's always a better way to do it, but ignorance
is bliss."
My bronze rule is "Please refer to the aforementioned two rules."


On Wed, 20 Oct 2004 21:54:06 -0300, André Roberge
<andre.roberge at ns.sympatico.ca> wrote:
> Dear Tutors,
> 
> (I won't repeat the whole message, which you should just have gotten -
> or is above in the digest version)
> 
> I changed the first script, added a third and it now works the way I
> expect when I run the third.  Below is my attempt at explaining what
> happened - I would really appreciate any correction!
> 
> ===Script1.py ===
> def printfoo():
>     print "foo"
> def run_test():  # this line is the only change, other than indent
>     execfile("Script2.py")
> 
> ===Script2.py===           # no change here
> from Script1 import *
> print "starting"
> printfoo()
> print "done"
> 
> ====Script3.py======
> from Script1 import *
> run_test()
> =====================
> 
> Before, when I ran script1 (without the def run_test()),
> execfile(...) was run *once* when Script2 was executed and imported
> Script1 in turn.  So, execfile was first run from the "import" statement
> in Script2, and then from its natural place in Script1.
> Since modules are only imported once, on subsequent runs, the import
> statement in Script2 was ignored, and I got the expected behaviour.
> 
> Now, in this new version, Script1 only contains definitions.  When it is
> imported in Script2 [line 1], nothing is printed.  When lines 2-4 are
> executed, I get the three printed lines, i.e.
> 
> starting
> foo
> done
> 
> which is what I wanted.
> 
> Is this close to being correct?
> 
> André Roberge
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list