Python 3中的解释器样式输出(可能关于sys.displayhook?) [英] Interpreter-style output in Python 3 (maybe about sys.displayhook?)

查看:282
本文介绍了Python 3中的解释器样式输出(可能关于sys.displayhook?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Tk制作一个小的玩具命令窗口,目前正试图使其复制某些解释器行为.

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 when to print a value are a little mystifying.

>>> 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'

目标是模仿这种行为,打印一些None,而不打印其他(由于我不太确定规则是什么,所以稍微复杂一些).

The goal is to mimic this behavior, printing some Nones, not others (made slightly more complicated because I'm not entirely sure what the rules are).

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

So, turning to my program, I have history_text and entry_text, which are StringVar()s that control a label above an entry box in the Tk window. Then the following event is bound to the Return key, to process commands and update the history with the result.

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"或"None"甚至"3 + 4"提供任何输出.一直在添加隐式的print()语句似乎经常打印,我不会跳过'None'或'a = 3'类型的语句的打印.

As is, it does not provide any output for a simple entry of '3' or 'None' or even '3 + 4'. Adding an implied print() statement all the time seems to print too often, I don't skip the print for 'None' or 'a = 3' type statements.

我找到了sys.displayhook的一些文档,该文档似乎控制着解释器何时实际显示结果,但是我不确定如何在这里使用它.我以为我可以将sys.displayhook()包裹在我的exec()调用周围,并让它为我完成所有这些工作...但是发现它并不暗示对诸如"3 + 4"或'3'.

I found some documentation for sys.displayhook, which seems to govern when the interpreter will actually display a result, but I'm not sure how to use it here. I thought I could just wrap sys.displayhook() around my exec() call, and have it do all this work for me... but found that it does not imply print() statements for statements like '3 + 4' or '3'.

有什么建议吗? sys.displayhook是否使我步入正轨?

Any suggestions? Am I on the right track with sys.displayhook?

推荐答案

仅当result is not None时,解释器才会打印出repr(result).

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

没有您想像的暗示的print s".

There are no "implied prints" like you thought.

  • 3 + 4结果为7,因此打印了repr(7)
  • a = 3是一项作业,我认为没有打印任何内容,因为它不适用于eval
  • None结果为None,所以什么也没打印
  • print(None)结果为None(因为print函数不返回任何内容),因此不打印任何内容.但是,print函数本身会打印None.
  • 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:

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

这篇关于Python 3中的解释器样式输出(可能关于sys.displayhook?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆