为什么在Interactive Python中返回会打印到sys.stdout?
问题内容:
我今天遇到了一些不同的事情。考虑以下简单功能:
def hi():
return 'hi'
如果我在Python shell中调用它,
>>> hi()
'hi'
>>> print hi()
hi
即使是,它也会打印出“返回的”值repr
。这让我感到奇怪, 如何将打印返回到stdout? 所以我将其更改为要运行的脚本:
def hi():
return 'hi'
hi()
我从终端运行了这个:
上次登录:ttys000上的Jun Jun 1 23:21:25
imac:〜zinedine $ cd文件
imac:documents zinedine $ python hello.py
imac:文档zinedine $
似乎没有输出。然后,我开始认为这是一个空闲的事情,因此我尝试了以下操作:
上次登录:ttys000上2月2日星期二13:07:19
imac:〜zinedine $ cd文件
imac:documents zinedine $ idle -r hello.py
这是空闲状态中显示的内容:
Python 2.7.6(v2.7.6:3a1db0d2747e,2013年11月10日,00:42:54)
达尔文[GCC 4.2.1(Apple Inc. build 5666)(dot 3)]
键入“版权”,“信用”或“ license()”以获取更多信息。
>>>
>>>
因此, 仅 在交互式python shell中返回打印。这是功能吗?这应该发生吗?这有什么好处?
问题答案:
交互式解释器将打印您键入并执行的表达式返回的所有内容,以方便测试和调试。
>>> 5
5
>>> 42
42
>>> 'hello'
'hello'
>>> (lambda : 'hello')()
'hello'
>>> def f():
... print 'this is printed'
... return 'this is returned, and printed by the interpreter'
...
>>> f()
this is printed
'this is returned, and printed by the interpreter'
>>> None
>>>
有关更多信息,请参阅Wikipedia上的“读取-
评估-打印”循环
。