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

Python 3.x Python 3中的解释器样式输出(可能是关于sys.displayhook?),python-3.x,interpreter,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

我正在用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'
我们的目标是模仿这种行为,打印一些非,而不是其他(由于我不完全确定规则是什么,所以变得稍微复杂一些)

因此,在我的程序中,我有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()语句似乎打印得太频繁了,我不会跳过“None”或“a=3”类型语句的打印

我找到了sys.displayhook的一些文档,它似乎控制解释器何时实际显示结果,但我不确定在这里如何使用它。我想我可以把sys.displayhook()包装在我的exec()调用中,让它为我完成所有这些工作。。。但发现对于像“3+4”或“3”这样的语句,它并不意味着print()语句


有什么建议吗?我使用sys.displayhook是否正确?

只有当
结果不是None时,解释器才会打印
repr(result)

没有你想象中的“隐含
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)

“解释器只有在结果不是None时才打印repr(result)”。我读过这篇文章,然后当我看到“print(None)”的行为时,我认为这不是真的。。。尽管你是对的,但是print()函数本身在那里打印None,这在事后看来是很明显的。不知道为什么我在这里会如此困惑;谢谢你让我重回正轨。