I saw a snippet of python which is used to execute another python
script, and I'm trying to understand the mechanism. Simple as it is, I
don't understand how it works :-)
this is the caller
##############################
callee=open("tester.py").read()
exec(callee)
eval("main(['', 'argument'])")
##############################
this is the callee which is saved in tester.py
##############################
import sys
def main(arg):
if arg != []:
print"\nArgument is %s" % arg
if __name__ == "__main__"":
main(sys.argv)
##############################
When the caller is executed
Argument is ['argument']
is displayed, as if the user had typed python tester.py
So I looked a the docs for read() in the file module for a clue-
didn't see anything obvious.
I usually use readlines() myself, so I thought read() might have some
hidden magic I wasn't aware of.
I understand exec() and eval() (in general), but I don't understand
how the entire tester.py gets read in when only a single call to
read() occurs.
Also- I don't understand how the call to eval() executes "in the scope
of" the main in tester.py. If the main in the eval call were
*somehow* qualified with something to provide scope to tester.py, It
would probably make sense.
Let's assume that the caller also has a main(). How does eval() know
to execute main in the scope of tester.py, and not in the scope of the
caller?
This is pretty cool and confusing ;-)
Is this a useful thing to do, or bad in practice?
thanks
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor