executing arbitrary statements

Jason Swails jason.swails at gmail.com
Sat Oct 1 02:31:18 EDT 2011


Hello everyone,

I'm probably missing something pretty obvious, but I was wondering if there
was a way of executing an arbitrary line of code somehow (such as a line of
code based on user-input).  There's the obvious use of "eval" that will
evaluate a function call, but that doesn't allow all things.  For instance:

>>> import sys
>>> eval(r"sys.stdout.write('Hello world!\n')")
Hello world!
>>> eval(r"print 'Hello world!'")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    print 'Hello world!'
        ^
SyntaxError: invalid syntax
>>>

Because write is a function eval works fine for it.  But since print isn't
(2.7), it throws a syntax error.  Likewise, variable assignments aren't
allowed either as they are also not functions and lack a return value:

>>> eval("j = 1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    j = 1
      ^
SyntaxError: invalid syntax

What I'm more or less looking to do is present a (limited) form of an
interpreter inside the application I'm writing for the advanced user.

I'm also interested to hear if this is a particularly bad idea for any
reason, and if there are security issues involved with allowing users to
execute their own code inside my program (keeping in mind that some people
may "donate" their scripts to others that may run them as black boxes).  Is
it enough to disallow import statements, thereby not giving direct access to
the sys and os modules?  I know more or less what I want to do, but I'd also
appreciate any experienced input/advice/suggestions.

Thanks!
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111001/421eabb6/attachment.html>


More information about the Python-list mailing list