簡體   English   中英

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

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

我正在嘗試編寫一個簡單的程序,該程序將在與python 2.7和3.3兼容的終端中顯示旋轉加載圖標。 我雖然可以from __future__ import print_function語句運行,但是我在python 2中得到的只是一個空行。 然后,我嘗試了sys.stdout.write但是它也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:]])

結果是:

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

$ # nothing shown

有沒有一種方法可以解決此問題而無需為每個版本創建兩個單獨的文件? 我在帶有python 2.7.8和3.3.1的linux centOS6上運行它。 提前致謝。

顯式flush sys.stdout似乎可以在Python 2中修復它:

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

print功能還具有flush參數:

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

但是,這似乎僅在Python 3中有效。 from __future__ import print_function導入的print版本似乎缺少此參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM