[Tutor] How does this work?

Alan Gauld alan.gauld at btinternet.com
Wed Feb 7 09:50:33 CET 2007


"Tony Cappellini" <cappy2112 at gmail.com> wrote

>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 :-)

Danny has explained that it is evil and shouldn't be used
but here goes on the explanation.

> ##############################
> callee=open("tester.py").read()

read)() reads the *entire* file in as a string
(complete with embedded newlines etc)

> exec(callee)

executes the file with any function/class definitions left
for future use.

> eval("main(['', 'argument'])")

calls the main function defined by the exec() operation,
passing in the string 'argument'

> ##############################
> import sys
>
> def main(arg):
>   if arg != []:
>      print"\nArgument is %s" % arg

defines the main function that is to be called.

> if __name__ == "__main__"":
>   main(sys.argv)
> ##############################


> 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?

It doesn't. It relies on there being a main function in the
"imported" script and the caller not having created one himself.

> This is pretty cool and confusing ;-)
> Is this a useful thing to do, or bad in practice?

As Danny said, its very very bad.
Imagine someone replacing tester.py with something like:

##############
import os
if os.system('format c:'):   # kill DOS
   os.system('rm -rf /')      # kill *nix

def main(): print "Sucker!!!"
###############

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list