How can I clear a line in console after using \r and printing some text?

2024/9/8 10:29:33

For my current project, there are some pieces of code that are slow and which I can't make faster. To get some feedback how much was done / has to be done, I've created a progress snippet which you can see below.

When you look at the last line

sys.stdout.write("\r100%" + " "*80 + "\n")

I use " "*80 to override eventually remaining characters. Is there a better way to clear the line?

(If you find the error in the calculation of the remaining time, I'd also be happy. But that's the question.)

Progress snippet

#!/usr/bin/env pythonimport time
import sys
import datetimedef some_slow_function():start_time = time.time()totalwork = 100for i in range(totalwork):# The slow parttime.sleep(0.05)if i > 0:# Show how much work was done / how much work is remainingpercentage_done = float(i)/totalworkcurrent_running_time = time.time() - start_timeremaining_seconds = current_running_time / percentage_donetmp = datetime.timedelta(seconds=remaining_seconds)sys.stdout.write("\r%0.2f%% (%s remaining)   " %(percentage_done*100, str(tmp)))sys.stdout.flush()sys.stdout.write("\r100%" + " "*80 + "\n")sys.stdout.flush()if __name__ == '__main__':some_slow_function()

Consoles

I use ZSH most of the time, sometimes bash (and I am always on a Linux system)

Answer

Try using the ANSI/vt100 "erase to end of line" escape sequence:

sys.stdout.write("\r100%\033[K\n")

Demonstration:

for i in range(4):sys.stdout.write("\r" + ("."*i*10))sys.stdout.flush()if i == 3:sys.stdout.write("\rDone\033[K\n")time.sleep(1.5)

Reference: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

https://en.xdnf.cn/q/72727.html

Related Q&A

installing pyaudio to docker container

I am trying to install pyaudio to my docker container and I was wondering if anyone had any solution for Windows. I have tried two methods: Method 1: Using pipwin - Error Code: => [3/7] RUN pip inst…

Escaping special characters in elasticsearch

I am using the elasticsearch python client to make some queries to the elasticsearch instance that we are hosting.I noticed that some characters need to be escaped. Specifically, these...+ - &&…

Interacting with live matplotlib plot

Im trying to create a live plot which updates as more data is available.import os,sys import matplotlib.pyplot as pltimport time import randomdef live_plot():fig = plt.figure()ax = fig.add_subplot(111)…

pandas groupby: can I select an agg function by one level of a column MultiIndex?

I have a pandas DataFrame with a MultiIndex of columns:columns=pd.MultiIndex.from_tuples([(c, i) for c in [a, b] for i in range(3)]) df = pd.DataFrame(np.random.randn(4, 6),index=[0, 0, 1, 1],columns=c…

Bottle web app not serving static css files

My bottle web application is not serving my main.css file despite the fact I am using the static_file method.app.pyfrom bottle import * from xml.dom import minidom @route(/) def index():return template…

How to wrap text in OpenCV when I print it on an image and it exceeds the frame of the image?

I have a 1:1 ratio image and I want to make sure that if the text exceeds the frame of the image, it gets wrapped to the next line. How would I do it?I am thinking of doing an if-else block, where &qu…

pandas series filtering between values

If s is a pandas.Series, I know I can do this:b = s < 4or b = s > 0but I cant dob = 0 < s < 4orb = (0 < s) and (s < 4)What is the idiomatic pandas method for creating a boolean series…

python os.path.exists reports False when files is there

Hi have an application which is sometimes reporting that a file does not exist even when it does, I am using os.path.exists and the file is on a mounted network share. I am on OSX Yosemite, python 2.7.…

Python unhashable type: numpy.ndarray

I worked on making functions for K Nearest Neighbors. I have tested each function separately and they all work well. However whenever I put them together and run KNN_method, it shows unhashable type: n…

Efficient way to generate Lime explanations for full dataset

Am working on a binary classification problem with 1000 rows and 15 features. Currently am using Lime to explain the predictions of each instance. I use the below code to generate explanations for full…