2010-11-27 1 views
0

なぜ私のPythonクロックはPython2からしか動かないのですが、Python3は何もしません。バックスペースの問題

from __future__ import print_function 
import time 
wipe = '\b'*len(time.asctime()) 
print("The current date and time are: "+' '*len(wipe), end='') 
while True: 
    print(wipe+time.asctime(), end='') 
    time.sleep(1) 

答えて

4

Python 3では、印刷バッファをフラッシュして、文字を画面に強制的に書き込む必要があります。

は、スクリプトの先頭に

import sys 

を追加し、

while True: 
    print(wipe+time.asctime(), end='') 
    sys.stdout.flush() 
    time.sleep(1) 
+0

実際には、これはPython 2.xでも必要です(少なくともprint関数を使用している場合)。 –

+0

私のシステムでは、これがなければPython 2でも動作しません。 –

+0

私のシステム(Windows 7 x64)では、Python 2.7ではこれがなくても動作します。 –

1

にループを変更する問題は、Pythonのバージョンではなく、むしろ、あなたは標準出力をフラッシュするのを忘れていること。コードを次のように変更してみてください:

from __future__ import print_function 
import time 
import sys 
wipe = '\b'*len(time.asctime()) 
print("The current date and time are: "+' '*len(wipe), end='') 
while True: 
    print(wipe+time.asctime(), end='') 
    sys.stdout.flush() 
    time.sleep(1) 

sys.stdout改行が印刷されたときだけフラッシュします。

関連する問題