简体   繁体   English

如何在python 2和3中都覆盖?

[英]How to overwrite in both python 2 and 3?

I'm trying to write a simple program that will display a rotating loading icon in the terminal that is compatible with both python 2.7 and 3.3. 我正在尝试编写一个简单的程序,该程序将在与python 2.7和3.3兼容的终端中显示旋转加载图标。 I would have though the from __future__ import print_function statement would work but all I get in python 2 is a blank line. 我虽然可以from __future__ import print_function语句运行,但是我在python 2中得到的只是一个空行。 I then tried sys.stdout.write but that also comes up blank. 然后,我尝试了sys.stdout.write但是它也sys.stdout.write空白。

Here is my reduced code: 这是我的简化代码:

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:]])

and this is the result: 结果是:

$ python3 load_icon.py
/
$ # a rotating line
$ python2 load_icon.py

$ # nothing shown

Is there a way to solve this without creating two seperate files for each version? 有没有一种方法可以解决此问题而无需为每个版本创建两个单独的文件? I am running this on linux centOS6 with python 2.7.8 and 3.3.1. 我在带有python 2.7.8和3.3.1的linux centOS6上运行它。 Thanks in advance. 提前致谢。

Explicitly flush ing sys.stdout seems to fix it in Python 2: 显式flush sys.stdout似乎可以在Python 2中修复它:

            sys.stdout.write('\r{} '.format(symbol))
            sys.stdout.flush()

The print function also has a flush parameter: print功能还具有flush参数:

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

However, this seems to work only in Python 3. The version of print imported with from __future__ import print_function seems to be missing this parameter. 但是,这似乎仅在Python 3中有效。 from __future__ import print_function导入的print版本似乎缺少此参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM