How to exec() a string like interactive python does?



If I start Python in interactive mode,
and I yype the commands,
'a=3', 'a', 'print a'


Then the output would look like:
>>> a = 3
>>> a
3
>>> print a
3


Now within an application I'd like to achieve exactly this behaviour
Meaning, that
- for assignments nothing is displayed
- for expressions the result of the exprission displayed
- and statements like print statements would be executed


The only thing, that I came up with is following code and that would
even print out results for 'a=3', where the normal interactive python would not echo any result.

for cmd in [ 'a=3', 'a', 'print a' ] :
try:
print('>>> ' + cmd)
exec('__rslt = ' + cmd)
if __rslt is not None:
print repr(__rslt)
except SyntaxError:
exec(cmd)

The result would look like:
>>> a=3
3
>>> a
3
>>> print a
3
>>>


Is There anything better?





.



Relevant Pages

  • Re: I see advice on how to debug a python module that hangs up the process
    ... >> The first step I'd suggest is to sprinkle print statements all around ... >> later perusal) and see when the thing hangs. ... You could also run python with -u so you're sure to get all the output flushed immediately, ... >>> def ptrace: ...
    (comp.lang.python)
  • Strange problem with interactive mode, possible bug in Python?
    ... I have a strange problem with Python command-line interactive mode. ... Attempting to startup JVM ... SyntaxError: invalid syntax ...
    (comp.lang.python)
  • Python, Tkinter and popen problem
    ... Python version is 2.5.2, Tinker in that package. ... not and has never shown signs of connection to stdin OF child ... The Tkinter usage has three print statements. ...
    (comp.lang.python)
  • Re: Toward a 21st century Forth
    ... where's the amateur interest for amateur tools aimed ... say we want to compete head-on with Python at what Python does ... print statements and they added the nice _ expression. ... user to remember well over a hundred stack diagrams. ...
    (comp.lang.forth)
  • Re: Debugging a Python Program that Hangs
    ... I have no idea where it is hanging, ... simply putting in print statements to locate the spot would be quite ... Looking through the python debugger documentation, ... Is there a way to stop within a running python ...
    (comp.lang.python)