Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

python - Overwriting/clearing previous console line

My problem is, that I want to be able to overwrite/clear previous printed line in python console. This question has been asked many times (Python - Remove and Replace Printed items for example), however with the very same code that is (the answer marked as correct, for me prints out nothing at all):

for i in range(10):
    print("Loading" + "." * i)
    time.sleep(1)
    sys.stdout.write("33[F") # Cursor up one line
    sys.stdout.write("33[K") # Clear to the end of line

I get the output (In python IDLE) :

Loading
[F[KLoading.
[F[KLoading..
[F[KLoading...
[F[KLoading....
[F[KLoading.....
[F[KLoading......
[F[KLoading.......
[F[KLoading........
[F[KLoading.........
[F[KLoading..........
[F[K

Any ideas? I googled a lot, nothing works really. It either prints out nothing or just does not overwrite.

If that helps, I am running windows 8.1 and Python 3.51. Running the code trough cmd doesn't affect anything.

Also, adding sys.stdout.flush() does not help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to run your program form the command line, not from within IDLE.

Then, this should work:

import sys
import time

for i in range(10):
    sys.stdout.write("
" + "Loading" + "." * i)
    time.sleep(1)
    sys.stdout.flush()
print()

The goes to beginning of the line. So you have to make sure the string you print is at least as long as the one before. Otherwise, you will see parts of the previous print.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...