skip to Main Content

I am taking input from user in python code. and as per user’s provided input I want to clear previous outputs in terminal.

so is there any function? So I can put it in my code.

I searched on internet but it showing me Shortcut keys from keyboard but I want to clear terminal with help of code.(not want to type terminal )

2

Answers


  1. The commands will be slightly different depending on if you’re running Python in Windows or Linux/Mac (or a Unix like terminal while in Windows)

    • In Windows terminals, the command to clear the screen is cls.
    • In Max/Linux/Unix, the command is clear.
    • Windows Powershell appears to
      except either cls or clear.

    To call the appropriate command from within a script, you need to import the os module and call os.system(cmd). This will return a value of 0 for success, so if you are testing it in the terminal directly you may see an extra 0 get displayed on the screen if you don’t put the return value into a variable.

    Here’s some code to call the correct function based on your os. os.name will return ‘nt’ for Windows or ‘posix’ for Mac/Linux

    import os
    
    # define our clear function
    def clear():
        # for Windows
        if os.name == 'nt':
            _ = os.system('cls')
    
        # Mac or Linux (aka posix)
        else:
            _ = os.system('clear')
    

    Calling the clear() function in your script should clear the terminal as needed.

    Login or Signup to reply.
  2. You can clear the terminal with:

    print('x1b[Hx1b[2J', end='')
    

    …or…

    from sys import stdout
    stdout.write('x1b[Hx1b[2J')
    

    …which is probably more efficient than os.system(…)

    The string is actually 2 CSI sequences. The first moves the cursor to the screen origin (1, 1). The second sequence is the clear screen directive

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search