Search code examples
python-3.xinputtext

After I enter an input in python, how do I clear it from my CLI?


In a script like this:

inp = input('')
print(inp)

When I run it, I enter my text and get it back:

$python3 test.py

Hello            (keyboard input)
Hello            (Print command)

But how do I get the result more like this after I press enter:?

$python3 test.py

Hello            (Print command)

Solution

  • There are a few options. The most straightforward one is to omit the print statement and just use:

    inp = input('')
    

    If you'd like to hide the input from the terminal as you're typing, you may use getpass():

    from getpass import getpass
    inp = getpass()
    print(inp)
    

    Or you may clear the whole terminal after reading the input like so:

    import os
    
    inp = input('')
    os.system('cls' if os.name == 'nt' else 'clear')
    print(inp)
    

    Or just delete the last line - I think this is the solution you're looking for:

    inp = input('')
    print ("\033[A                             \033[A")
    print(inp)