Home > OS >  clean screen from previous output in a loop in python
clean screen from previous output in a loop in python

Time:07-20

I have a for loop that iterate through the rows of dataframe containing some texts and shows the user texts associated with specific indices. The users should provide some labels to the text in each iteration of the loop.

As some of the texts presented to the users are long, before going to the next text, I want to clear screen such that each text is shown individually on the screen. I was doing some tests with the code below which simulates my problem, but I did not get the expected result:

import os
from time import sleep

list_texts=['a','b','c','d','e','f','g']

for i in list_texts:
  print(i)
  l=input('Please, enter labels here: ')
  sleep(2)
  clear()
  u=input('Continue? y/n: ')
  if u == 'y':
    continue
  else:
    print('See you later')
    break

My desired output is the text a the question 'Please, enter labels here: ' without the previous output. Thanks in advance for any help.

CodePudding user response:

Okay so just to make sure I understood the question correctly, please correct me if I'm wrong:

The desired output per iteration in the example is the next piece of text followed by Please, enter labels here on the screen without anything else from the previous iterations.

We can do something like this:

import os

if __name__ == "__main__":

   
    list_texts=['a','b','c','d','e','f','g']

    for i in list_texts:
        os.system('cls' if os.name == 'nt' else 'clear')
        print(i)
        l=input('Please, enter labels here: ')
        u=input('Continue? y/n: ')

        if u == 'n':
            print('See you later')
            break

Output:

a
Please, enter labels here: test
Continue? y/n: y

Followed by:

b
Please, enter labels here:

And so on for each iteration.

The line os.system('cls' if os.name == 'nt' else 'clear') empties the terminal screen at the beginning of every iteration by running cls if you're using a Windows machine and clear if you're using a Unix based one.

The post Clear terminal in Python is a good reference for these types of terminal manipulations (commented earlier by @Adam).

EDIT: Specifically because the environment desired is google colab, this appears to work better on that setup:

from google.colab import output
 
if __name__ == "__main__":

   
    list_texts=['a','b','c','d','e','f','g']

    for i in list_texts:
        output.clear()
        print(i)
        l=input('Please, enter labels here: ')
        u=input('Continue? y/n: ')

        if u == 'n':
            print('See you later')
            break

This post specifically is good for for further information: How to clear the output in Google Colab via code?

  • Related