3

When running a Python REPL, top-level statements sent to the console get auto-printed. For example, with:

>>> x = 1
>>> x
1
>>> |

The second line evaluating x caused the value to be 'auto-printed' However, we don't get the same behavior when x is evaluated in other contexts -- for example, if we use exec:

>>> exec('x')
>>> |

Similarly, with eval():

>>> code = compile('x = 1; x', '<string>', 'exec')
>>> eval(code)
>>> |

Is there a way to ask Python to auto-print statements run in this way, as it does at the top level of the REPL?

While this question describes Python code directly, I'd also love to know whether it's possible to accomplish this using the Python C API (e.g. with PyRun_SimpleStringFlags()).

Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88
  • Possible duplicate of [What's the difference between eval, exec, and compile in Python?](https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python) – TemporalWolf Feb 14 '18 at 22:53
  • tl;dr: the console only shows non-`None` results. `exec` always returns `None`. `eval`ing `exec` is still `None`. – TemporalWolf Feb 14 '18 at 22:57

1 Answers1

0

This is discussed in some detail at https://stackoverflow.com/a/29456463/1342082. In particular:

'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

So a pattern of this form will work:

>>> code = compile('x = 1; x', '<string>', 'single')
>>> eval(code)
1
>>> |

And also see the documentation described at https://docs.python.org/3/library/functions.html#eval.

Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88