Skip to content Skip to sidebar Skip to footer

Interpreter-style Output In Python 3 (maybe About Sys.displayhook?)

I'm making a little toy command window with Tk, and currently trying to make it copy some interpreter behavior. I'd never scrutinized the interpreter before, but it's decisions on

Solution 1:

The interpreter prints out repr(result) only if result is not None.

There are no "implied prints" like you thought.

  • 3 + 4 results to 7, so repr(7) is printed
  • a = 3 is an assignment, I think nothing is printed because it does not work with eval
  • None results to None, so nothing is printed
  • print(None) results to None (because the print function returns nothing), so nothing is printed. However, the print function itself printed the None.

I honestly didn't read your code, but here's a function that takes a string with code and produces the same output as the interpreter would:

definteractive(code):
    try:
        result = eval(code)
        if result isnotNone:
            print(repr(result))
    except SyntaxError:
        exec(code)

Post a Comment for "Interpreter-style Output In Python 3 (maybe About Sys.displayhook?)"