Muchdecal
Muchdecal

Reputation: 177

how to delete or clear printed text in python

I'm learning python in Jupyterlab. Currently, I tried to find a way to clear the printed text in Jupyterlab but I haven't gotten any luck.

I searched online to find a few solutions. However, they won't clear the printed text in my console even though others have reported position results.

I tried the (1). '\b' character (2)os.system('cls') (3)sys.stdout.write

all of them failed to clear the printed text.

print('Hello',end='')
print(5*'\b')
print('how are you?',end='')

output: Hell how are you?

print('Hello',end='')
for i in range(len('Hello')):
    print('\b',end='')

print('how are you?',end='')

output: Hellhow are you?

print('Hey')
import os
if os.name=='nt':
    os.system('cls')
else:
    os.system('clear')
print('how are you?')

output: Hey how are you?

import sys, time

def delete_last_line():
    sys.stdout.write('\x1b[1A')
    sys.stdout.write('\x1b[2K')

print("hello")
time.sleep(2)
delete_last_line()
print("how are you")

output: hello how are you

I wonder if it's because the system or modules have updated so that the methods no longer work the same way or my computer or Jupyterlab has bugs causing the failure.

Upvotes: 6

Views: 7490

Answers (3)

Duplexsoup
Duplexsoup

Reputation: 1

This is an easy way to fix the problem:

import time
x = 0
for i in range(100):
    print(f'{x}% loaded', end= "\r", flush = True)
    x += 1
    time.sleep(0.5)

Upvotes: 0

Geekmoss
Geekmoss

Reputation: 682

Be careful of the length, \r the cursor returns to the beginning of the line, but it is not overwritten, it is overwritten only from the beginning with the entered text.

print('Hello', end='\r')
# >>> Hello
print('How are you?', end='\r')
# >>> How are you?
print('TEST', end='\r')
# >>> TESTare you?

Maybe I would suggest an auxiliary function:

def echo(string, padding=80):
    padding = " " * (padding - len(string)) if padding else ""
    print(string + padding, end='\r')

echo("Hello")
# >>> Hello
echo("How are you?")
# >>> How are you?
echo("TEST")
# >>> TEST

Upvotes: 7

ToughMind
ToughMind

Reputation: 1009

I tried this way and succeed:

import sys

sys.stdout.write('hello\r')
sys.stdout.flush()
sys.stdout.write('how are you\r')

>>>how are you

you need to use the sys.stdout.write(info + '\r') to output the information. '\r' means back to the begin of the line without changing lines.

Upvotes: 0

Related Questions