exec considered harmful

Nick Perkins nperkins7 at home.com
Tue Jul 24 18:02:02 CEST 2001


"Aquarius" <aquarius at kryogenix.org> wrote in message
news:9jjo5b$jn3$1 at giles.kryogenix.org...
> I've got a CGI which reads a file and then execs its contents. The file
> defines a function, and that function can't find itself to call
> recursively; it gets a NameError.
>
> Example:
>
> [ aquarius at giles ] /home/httpd/kryogenix.org/current/web $ cat foo.cgi
> #! /usr/bin/python
>
> import sys
> sys.stderr = sys.stdout
>
> print "Content-type: text/html\n\n"
>
>
> def main():
>     fp = open("foo.txt")
>     exec(fp.read())
>
> main()
>
> [ aquarius at giles ] /home/httpd/kryogenix.org/current/web $ cat foo.txt
>
> def bar(quux=None):
>     if quux == "test":
>         print "Hello, world!"
>     else:
>         bar("test")
>
> bar("nothing")
>
> [ aquarius at giles ] /home/httpd/kryogenix.org/current/web $ python foo.cgi
> Content-type: text/html
>
>
> Traceback (innermost last):
>   File "foo.cgi", line 13, in ?
>     main()
>   File "foo.cgi", line 11, in main
>     exec(fp.read())
>   File "<string>", line 8, in ?
>   File "<string>", line 6, in bar
> NameError: bar
>
> My question here is: is there anything I can do about this? I assume
> that you can't call bar() from inside bar() because it only knows about
> two namespaces, global (which main() is in) and the "inside-bar()"
> namespace, and bar() itself is in neither. I've tried this with both
> 1.5.2 and 2.0.1 and there doesn't appear to be any different (aside
> from the wording of the NameError changing to "There is no variable
> named 'bar'" under 2.0.1, which I assume is the same thing).
>
> Aq -- I wish I understood namespaces
>
> --
> "The grand plan that is Aquarius proceeds apace"
>             -- Frank Miller, "Ronin"


why exec(), when you can import?

I think that people with experience in Perl tend to want to exec() too much.
If you have a function in another file that you want to execute, you should
make that other file a .py file, and import it.

In the old days, we had "GOTO Considered Harmful",
today, in Python, I thing we need "exec() Considered Harmful".
( but maybe that's just me..
  I have done a fair bit of Python, and *never* used exec() or eval() )






More information about the Python-list mailing list