1

I would like to know if it is possible to limit the amount of time a print statement appears in the user console. I have a project that is a Contact Manager and it used a CSV file to store the contact data. The program is designed to create a new CSV file in the even that one is not available in the directory. If I run the program without the CSV file in the directory I have the console display a message to the user letting them know that a new file was created. I would like to have this message only display for maybe 10 seconds or so then disappear from the console. Is this possible? If so I would appreciate some suggestions. Below is the portion of the code that checks for the CSV file then creates a new one and notifies the user if a new one has been created.

    def read_contacts():
        try:
           contacts = []
           with open(FILENAME, newline="") as file:
                reader = csv.reader(file)
                for row in reader:
                    contacts.append(row)
           return contacts
        except FileNotFoundError:
           print("Could not find " + FILENAME + " file!\n + "Starting new contacts file...\n")

At this point the code continues to create a new CSV file. What I would like to do is have the previous print statement disappear after 10 seconds so that it doesn't display in the console the entire time the program is running.

4 Answers4

1

You can use the carriage return ("\r") to go back to the beginning of the printed line, wait for 10 seconds, and then replace the text.

Example:

import time
def read_contacts():
    try:
        contacts = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError:
        msg = "Could not find " + FILENAME + " file! Starting new contacts file..."
        print(msg, end="\r")
        time.sleep(10)
        print(" " * len(msg), end="\r")
yurgen
  • 108
  • 1
  • 4
  • Thank You for your input. I tried this way but in may case it just gives a 10 second delay after printing the 'msg' prior to starting the actual program. – E.j. Caudle Oct 24 '18 at 18:21
0

If you're not on windows, you can look into curses. There is also a port for windows called unicurses.

WeRelic
  • 290
  • 1
  • 12
0

Another alternative approach can be using the \033[F character: (Since you do not want the delay to interrupt the remaining script, take advantage of python threading library)

import sys
import time
import threading

def func():
    time.sleep(10)
    sys.stdout.write("\033[F")

def read_contacts():
    try:
       contacts = []
       with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
       return contacts
    except FileNotFoundError:
       errmsg="Could not find " + FILENAME + " file!\n + "Starting new contacts file...\n"
       print(errmsg)
       t = threading.Thread(target=func)
       t.start()
       #remaining code
  • Thank You, in my case this gives a 10 second delay prior to starting the remainder of the program. The message still displays after that. – E.j. Caudle Oct 24 '18 at 18:22
  • I have modified my answer according to your requirement. Give this a try. **Note: I have assumed you don't have any prints after the line `print(errmsg)`**. – Susmita Bhattacharjee Oct 25 '18 at 14:28
  • Thank You for the update, I may be still doing something wrong or missing something because I changed my code to what you have provided and I am not getting a change in the function. It still works like before with the error message coming up and staying for the entirety of the program. – E.j. Caudle Oct 25 '18 at 15:59
  • \033[F is unable to remove '\n' characters. Got this after some trial and error. Hence in your case, try using `print("\033[3A\033[K")` instead of `sys.stdout.write("\033[F")`. Also, if you are using python3.x, have a look at this one using curses: https://stackoverflow.com/questions/6840420/python-rewrite-multiple-lines-in-the-console – Susmita Bhattacharjee Oct 26 '18 at 09:03
0

Simplest solution is to use sys module.

import sys
import time

FILENAME = "build_local.sh"


def disappear(msg: str, seconds: int = 3):
    # Multiple lines cannot be flushed from screen without leaving empty gaps
    msg = msg.replace('\n', '\t').strip()
    sys.stdout.write(f"\r{msg}")
    time.sleep(seconds)
    sys.stdout.write("\r")
    sys.stdout.flush()
    # Don't use print after flush as it will make future messages print on top of previous
    sys.stdout.write("\rTimed wait is done")


def read_contacts():
    try:
        contacts = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError:
        disappear(msg=f"Could not find {FILENAME} file!\nStarting new contacts file...")


if __name__ == '__main__':
    read_contacts()
Vignesh Rao
  • 136
  • 3