开发者

Backspace trouble

开发者 https://www.devze.com 2023-01-27 09:45 出处:网络
Why this my Python clock runs only from Python2, Python3 does nothing. from __future__ import print_function

Why this my Python clock runs only from Python2, Python3 does nothing.

from __future__ import print_function
import time
wipe = '\b'*len(time.asctime())
print("The current date and time are: "+' '*len(wipe), end='')
whi开发者_运维百科le True:
    print(wipe+time.asctime(), end='')
    time.sleep(1)


In Python 3, you need to flush the print buffer to force the characters to be written to the screen.

Add

import sys

to the start of your script and change the loop to

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


The problem is not with the python version, but rather that you forgot to flush the standard output. Try changing your code to:

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 only flushes when a newline is printed too.

0

精彩评论

暂无评论...
验证码 换一张
取 消