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
697 views
in Technique[技术] by (71.8m points)

printing - Unprint a line on the console in Python?

Is it possible to manipulate lines of text that have already been printed to the console?

For example,

import time
for k in range(1,100):
     print(str(k)+"/"+"100")
     time.sleep(0.03)
     #>> Clear the most recent line printed to the console
print("ready or not here I come!")

I've seen some things for using custom DOS consoles under Windows, but I would really like something that works on the command_line like does print without any additional canvases.

Does this exist? If it doesn’t, why not?

P.S.: I was trying to use curses, and it was causing problems with my command line behaviour outside of Python. (After erroring out of a Python script with curses in it, my Bash shell stopped printing newline -unacceptable- ).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What you're looking for is:

print("{}/100".format(k), "
", end="")

is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. end="" is to prevent after printing (to stay on the same line).

A simpler form as suggested by sonrad10 in the comments:

print("{}/100".format(k), end="
")

Here, we're simply replacing the end character with instead of .

In Python 2, the same can be achieved with:

print "{}/100".format(k), "
",

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

...