【发布时间】:2013-11-17 19:08:23
【问题描述】:
我在 Python 3.2 中观察到 __future__ 模块的 print_function 的奇怪行为。
以这段代码为例:
from __future__ import print_function
import sys
print('Enter the base path of the images: ', end='')
path = sys.stdin.readline().strip().strip('"')
if len(path) == 0:
print("No path entered")
else:
print(root)
print("\n\nPress ENTER to exit")
exit = sys.stdin.readline()
当脚本运行时,控制台似乎在等待用户按 ENTER,然后才显示第一个 print 语句。
然后输出如下所示:
今天不必要,向用户显示一个空提示会导致很多混乱,尤其是因为很多人害怕带有白色文本的黑色窗口(命令提示符)。
代码改成这个的时候
from __future__ import print_function
import sys
print('\nEnter the base path of the images: ', end='') #line now starts with \n
path = sys.stdin.readline().strip().strip('"')
if len(path) == 0:
print("No path entered")
else:
print(path)
print("\n\nPress ENTER to exit")
exit = sys.stdin.readline()
那么输出如预期(假设我们忽略前面的空行):
输入图像的基本路径:c:\ C:\ 按 ENTER 退出但是,当代码在 python 2.6 中运行时,第一个代码按预期工作(即它显示 Enter the base path of the images: 等待接收输入)。
这让我问:
为什么我需要在 print 函数前面加上 \n 才能在 Python 3.2 中显示输出,而在 Python 2.6 中运行时我不需要 \n?
难道是print_function在两个版本中的实现方式不同?
【问题讨论】:
-
您使用
sys.stdin.readline()而不是input有什么原因吗?大概是为了python2.x的兼容性? -
input在 Python 2 中尝试评估输入的任何内容(不是我想要的)。在 Python 3 中,它只是捕获输入(我想要的)。raw_input捕获输入(我想要的),但它只适用于 Python 2,而不是 3,所以很不方便。使用sys.stdin.readline()允许我在两个版本中使用相同的函数调用。
标签: python python-import