views:

46

answers:

1

I'm trying to use InteractiveConsole to create a new front-end for a Python interpreter. These code fragments are from me playing around with InteractiveConsole in IDLE:

>>> ses = code.InteractiveConsole()
>>> ses.runsource("def foo():")
True
>>> ses.runsource("    return 2")
  File "<input>", line 1
SyntaxError: 'return' outside function (<input>, line 1)
False

Why does it raise a syntax error? How else can I finish writing the function?

Also, for something like this:

>>> ses.runsource("x = 1")
False
>>> ses.runsource("x")
1
False

How can I capture the 1 value from above? False is the return value, but 1 is written to some stream.

Also, what would be the best way to serialize ses? I was thinking about supplying a locals dictionary, and saving that.

A: 

If you mean to use eval() or exec then do so. Only don't, because they're security problems.

Ignacio Vazquez-Abrams
What would make `eval?()` or `exec` better? If I ran `eval()` with its own dictionaries for globals and locals that were separate from the real global and local dictionaries, would that eliminate the security risk?
Rosarch
`eval()` and `exec` are designed for running arbitrary code. `code` is designed for showing a console to the end user. There's no way to completely secure them though, since Python provides mechanisms for retrieving parent stack frames.
Ignacio Vazquez-Abrams