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

Devin Jeanpierre jeanpierreda at gmail.com
Tue Jun 5 18:37:51 EDT 2012


>>>
>>> def myexec(s):
...     eval(compile(s, '<string>', 'single'))
...
>>> x = 3
>>> myexec('x = 4')
>>> myexec('x')
3
>>> myexec('print x')
3
>>>

On Tue, Jun 5, 2012 at 6:12 PM, News123 <news1234 at free.fr> wrote:
> 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?
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list