Python 3中的解释器样式输出(可能关于sys.displayhook?)

时间:2012-09-03 13:22:54

标签: python-3.x interpreter

我正在用Tk制作一个小玩具命令窗口,目前正试图让它复制一些翻译行为。

我之前从未仔细检查过翻译,但是决定何时打印一个值有点神秘。

>>> 3 + 4  # implied print(...)
7
>>> 3      # implied print(...)
3
>>> a = 3  # no output, no implied print(...), bc result is None maybe?
>>> None   # no output, no print(...) implied... doesn't like None?
>>> print(None)  # but it doesn't just ban all Nones, allows explicit print()
None
>>> str(None) # unsurprising, the string 'None' is just a string, and echoed
'None'

目标是模仿这种行为,打印一些Nones,而不是其他的(因为我不完全确定规则是什么,所以稍微复杂一些)。

所以,转到我的程序,我有history_text和entry_text,它们是StringVar(),它控制Tk窗口中输入框上方的标签。然后将以下事件绑定到Return键,以处理命令并使用结果更新历史记录。

def to_history(event):
    print("command entered")  # note to debugging window

    last_history = history_text.get()

    # hijack stdout
    buffer = io.StringIO('')
    sys.stdout = buffer

    # run command, output to buffer
    exec(entry_text.get())

    # buffered output to a simple string
    buffer.seek(0)
    buffer_str = ''
    for line in buffer.readlines():
        # maybe some rule goes here to decide if an implied 'print(...)' is needed
        buffer_str = buffer_str + line + '\n'

    # append typed command for echo
    new_history = entry_text.get() + '\n' + buffer_str

    # cleanup (let stdout go home)
    sys.stdout = sys.__stdout__
    buffer.close()

    history_text.set(last_history + "\n" + new_history)
    entry_text.set('')

原样,它不为“3”或“无”或甚至“3 + 4”的简单输入提供任何输出。一直添加隐含的print()语句似乎经常打印,我不会跳过“无”或“a = 3”类型语句的打印。

我找到了sys.displayhook的一些文档,它似乎控制了解释器实际显示结果的时间,但我不知道如何在这里使用它。我以为我可以围绕我的exec()调用包装sys.displayhook(),让它为我做所有这些工作......但发现它并不意味着像'3 + 4'这样的语句的print()语句或'3'。

有什么建议吗?我是否在sys.displayhook的正确轨道上?

1 个答案:

答案 0 :(得分:3)

解释程序仅在repr(result)时打印出result is not None

没有像你想的那样“暗示print s。”

  • 3 + 4结果为7,因此repr(7)已打印
  • a = 3是一项作业,我认为没有打印任何内容,因为它不适用于eval
  • None结果为None,因此无法打印任何内容
  • print(None)结果为None(因为print函数不返回任何内容),因此不打印任何内容。但是,print函数本身会打印None

老实说,我没有读过您的代码,但这里的函数采用带代码的字符串并产生与解释器相同的输出:

def interactive(code):
    try:
        result = eval(code)
        if result is not None:
            print(repr(result))
    except SyntaxError:
        exec(code)