Skip to main content
 首页 » 编程设计

python之为什么在 Interactive Python 中返回会打印到 sys.stdout

2025年05月04日9soundcode

我今天遇到了一些不同的事情。考虑这个简单的函数:

def hi(): 
    return 'hi' 

如果我在 Python shell 中调用它,

>>> hi() 
'hi' 
>>> print hi() 
hi 

它打印出“返回”值,即使它只是 repr。这对我来说很奇怪,返回怎么会打印到标准输出?所以我将它更改为要运行的脚本:

def hi(): 
    return 'hi' 
hi() 

我从终端运行这个:

Last login: Mon Jun  1 23:21:25 on ttys000 
imac:~ zinedine$ cd documents 
imac:documents zinedine$ python hello.py 
imac:documents zinedine$  

貌似没有输出。然后,我开始认为这是一件空闲的事情,所以我尝试了这个:

Last login: Tue Jun  2 13:07:19 on ttys000 
imac:~ zinedine$ cd documents 
imac:documents zinedine$ idle -r hello.py 

这是 Idle 中显示的内容:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)  
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "copyright", "credits" or "license()" for more information. 
>>>  
>>>  

所以在交互式 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 
>>> 

参见 Read–eval–print loop在维基百科上获取更多相关信息。