kamal MKA
kamal MKA

Reputation: 23

How can I overwrite a text after it's printed a few lines before?

I want to make a task/time manager. I want the list of tasks to be at the top and a question to add a new task if the user wants, but the problem is that I can't keep my to-do list in the top and I can't make it updated. What should I do?

This is my code, this is the form I want and the code I've written:

TASKS:(I want this to be updated)
1)--------
2)----------
3)----------
|
v
do you want to add a task(YES/NO):
when do you want to start the task (HOUR:MINUTE):
task_num = 0
k = False
print("YOUR TASKS")
if k == True:
    print("\r", tasks)
print("tasks" + ":" + str(task_num), "\n\n")
active = True
while active:
    add_task = input("do you want to add a task(YES/NO):",)
    if add_task != 'YES':
        active = False
    else:
        k = True
        start_time = input("when do you want to start the task (HOUR:MINUTE):")
        end_time = input("when do you want to complete it:")
        task_name = input("what do you want to call it:")
        start_h, start_m = start_time.split(":")
        end_h, end_m = end_time.split(":")
        duration = str(abs(int(end_h) - int(start_h))) + ":" + str(abs(int(end_m) - int(start_m)))
        task = {"task name": task_name, "start time": start_time, "end time": end_time, "duration": duration}
        task_num += 1
        tasks[task_num] = task
        for key in tasks.keys():
            task_key = tasks[key]
            print(key,end=")")
            for key1 in task_key.keys():
                print(key1, ":", task_key[key1], end='|',)
            print('\n')

Upvotes: 1

Views: 56

Answers (1)

mwo
mwo

Reputation: 456

On POSIX systems clear -x command works like a charm. It preserves the current scroll buffer and produces almost zero flickering. Combine that with hiding the cursor, ah it is marvelous.

import sys
import subprocess

try:
    sys.stdout.write('\033[?25l')  # hide cursor
    subprocess.run(['clear', '-x'])
finally:
    sys.stdout.write('\033[?25h')  # show cursor
    sys.stdout.flush()

On Windows, on the other hand, you'll probably need colorama package installed and initialized.
See https://github.com/tartley/colorama

On Windows cmd:

import sys
import shutil

height = shutil.get_terminal_size().lines
h = height * '\n'
# move cursor down and up.
sys.stdout.write(f'{h}\033[{height}A')
sys.stdout.flush()

On Windows Terminal and other modern terminal emulators:

import sys
import shutil

height = shutil.get_terminal_size().lines
# clear the screen with the ANSI sequence.
sys.stdout.write((height - 1) * '\n' + '\033[2J')
sys.stdout.flush()

Play with them and see what works for you.

Upvotes: 2

Related Questions