如何在Python2和Python3中覆盖?

如何在Python2和Python3中覆盖?,python,Python,我试图编写一个简单的程序,在终端中显示一个旋转加载图标,该图标与python 2.7和3.3兼容。我本来认为from\uuuuuu future\uuuuu导入print\u函数语句可以工作,但在python 2中我得到的只是一个空行。然后我尝试了sys.stdout.write,但结果也是空的 以下是我的简化代码: from __future__ import print_function import time import sys import itertools def load_ic

我试图编写一个简单的程序,在终端中显示一个旋转加载图标,该图标与python 2.7和3.3兼容。我本来认为
from\uuuuuu future\uuuuu导入print\u函数
语句可以工作,但在python 2中我得到的只是一个空行。然后我尝试了
sys.stdout.write
,但结果也是空的

以下是我的简化代码:

from __future__ import print_function
import time
import sys
import itertools

def load_icon(pause=0.5, timeout=None):
    tic = time.time()
    try:
        while (not timeout) or timeout < time.time() - tic:
            for symbol in itertools.cycle('\|/-'):
                ##print('\r{} '.format(symbol), end='') # Old version
                sys.stdout.write('\r{} '.format(symbol)) # New
                # Neither of the above work in py 2.7 yet do in py 3.3
                time.sleep(pause)
    except KeyboardInterrupt:
        pass
    finally:
        sys.stdout.write('\r    \n')

if __name__ == '__main__':
    load_icon(*[float(arg) for arg in sys.argv[1:]])

有没有一种方法可以解决这个问题,而不必为每个版本创建两个单独的文件?我在LinuxCentOS6上用Python2.7.8和3.3.1运行它。提前感谢。

明确地
flush
ing
sys.stdout
似乎在Python 2中修复了它:

            sys.stdout.write('\r{} '.format(symbol))
            sys.stdout.flush()
print
功能还有一个
flush
参数:

            print('\r{} '.format(symbol), end='', flush=True)

然而,这似乎只适用于Python3。使用“未来导入打印”功能导入的
导入的
打印版本似乎缺少此参数。

也许您只需要
刷新
?是的,这似乎有效。谢谢
            print('\r{} '.format(symbol), end='', flush=True)