How do I move the cursor 2 lines up to the beginning?
I have an application that outputs some data to the console, after which it turns on a timer to update the data. The whole output looks like this
Important data 1
Important data 2
Important data 3
Next update data after 01 minutes 51 seconds ...
To stop the program, press Ctrel+E
But there is a problem when the timer size becomes smaller, the line is not completely erased
Next update data after 55 seconds …seconds …
And it should be
Next update data after 55 seconds …
I know why this is happening, and I had an idea to avoid such an effect, I’ll just fill it with spaces before outputting a line.
I want to output empty lines to erase the old data and output an updated timer
clear_line_timer = ''.join(" " for i in range(len_line_timer))
clear_line_info = ''.join(" " for i in range(len_line_info))
line_timer = 'Next update data after ' + timerToString(seconds) + ' ...'
line_info = 'To stop the program, press Ctrl+E'
len_line_timer = len(line_timer)
len_line_info = len(line_info)
In theory, this should work, but I do not know how to return the cursor pointer to the beginning of the line with a timer.
How can I return the cursor to the beginning of the timer line before output?
I want it to work like in Windows and Linux/Unix
Full code for playback
import time
len_line_timer = 0
len_line_info = 0
def timerToString(seconds: int) -> str:
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}d {:02d}h {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}h {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d} minutes {:02d} seconds'.format(m, s)
elif s > 0:
return '{:02d} seconds'.format(s)
return 'now'
def timer(seconds):
global len_line_timer
global len_line_info
clear_line_timer = ''.join(" " for i in range(len_line_timer))
clear_line_info = ''.join(" " for i in range(len_line_info))
line_timer = 'Next update data after ' + timerToString(seconds) + ' ...'
line_info = 'To stop the program, press Ctrl+E'
len_line_timer = len(line_timer)
len_line_info = len(line_info)
####################################################################################
# You need to somehow return the cursor pointer to the beginning of the timer line #
####################################################################################
print(clear_line_timer + '\r', end='')
print(line_timer + '\r', end='')
print(clear_line_info + '\r', end='')
print(line_info + '\r', end='')
if __name__ == '__main__':
print("Important data 1")
print("Important data 2")
back_timer = 70
counter = back_timer
while True:
timer(counter)
counter -= 1
time.sleep(1)
if counter <= 0:
counter = back_timer