[Tutor] Help with python parsing please.. [hunting down a bug]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 21 Jul 2002 23:47:24 -0700 (PDT)


> Hmmm.... what does the 'commands' module look like?  Since that's the
> module responsible for evaluating strings, let's take a look at that
> module.

Hi SA,

Just doing a followup; I suddenly realized that commands.getoutput() is
meant to evaluate strings in the shell:

    http://www.python.org/doc/lib/module-commands.html


So commands.getoutput() is not meant to do Python stuff at all.  This is
why everything appears to be running through zsh: it is!  *grin*


You may want to check a previous version of the 'expyth()'
python-executing code that you had used a while back, like:

    http://mail.python.org/pipermail/tutor/2002-June/015009.html

Somewhere along the line, it looks like you switched from using
os.popen()'ing a python session to using commands.getoutput(), and that's
probably where the bug was introduced: things like 'print' still appeared
to work fine, but, behind the scenes, you were using zsh from that point
forward.  Switch it back to os.popen(), and things should go back to
normal.


But although os.popen() will work, if you want to evaluate Python strings,
perhaps the built-in 'exec()' execution function would work better for
you.  Here's an example of how we can use it:

###
>>> def my_python_exec(code_string):
...     """Evaluates a string as Python code, and returns its
... output as a string."""
...     old_stdout, new_stdout = sys.stdout, StringIO.StringIO()
...     sys.stdout = new_stdout
...     exec(code_string)
...     sys.stdout = old_stdout
...     return new_stdout.getvalue()
...
>>> some_code = """
... print "hello"
... def square(x): return x * x
... print "the square of 3 is", square(3)
... """
>>> my_python_exec(some_code)
'hello\nthe square of 3 is 9\n'
###


Be aware that I haven't put ANY security in here; any code that we send to
my_python_exec() has the exact same privileges as our own code.  This may
not be a Good Thing for the paranoid.

But then, it should be good enough for the moment; for more security, the
restricted execution module, 'rexec', is a better choice:

    http://www.python.org/doc/lib/module-rexec.html

We can talk about how to use 'rexec' if you'd like.



Good luck to you!