Ethan Baker
Ethan Baker

Reputation: 54

Clear current line in STDOUT in python

So I made a program in python that asks a user for input repetitively. After a while, the previous commands start to build up, as so.

> Ping
Pong!
> Hello
Hey there!
>say whats up?
Whats up?

I made the commands up just to show examples

I want to add an animation that adds a ... to the end of a word, such as

i choose.

then clear the line then

i choose..

then clear the line then

i choose...

and so on, but I need to clear the screen in order for this to work and I want the history of the users commands and responses to sill be there. Is there any way using python or importing os to only remove one line instead of the entire screen? Thanks!

Upvotes: 1

Views: 3285

Answers (3)

mr.dog233o5
mr.dog233o5

Reputation: 1

do this:

print("I choose", end="")
print(".", end="")
print(".", end="")
print(".", end="")

Upvotes: 0

John Stark
John Stark

Reputation: 1297

You should be able to do this using normal ‘print’, just appending a comma to the end of the print statement:

from time import sleep

print ‘I choose.’,  
sleep(0.5)
print ‘.’,  
sleep(0.5)
print ‘.’ 

Edit: Added in sleeps to make the animation work more as expected.

Upvotes: 0

Mia
Mia

Reputation: 2676

You are looking for the carriage return character, \r. When you print that character, the previous line will be cleared. For example:

import time
print('I choose',end='',flush=True)
time.sleep(1)
print('\rI choose.',end='',flush=True)
time.sleep(1)
print('\rI choose..',end='',flush=True)
time.sleep(1)
print('\rI choose...',end='',flush=True)

This is actually how people make the progress bar in command line.

Upvotes: 4

Related Questions