Tom
Tom

Reputation: 797

Python remove all console output

I want to erase all console output that was printed before each loop iteration.

Currently I have a code like this:

import sys
from time import sleep

def delete_last_printed_lines(n=1):
    CURSOR_UP_ONE = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'

    for _ in range(n):
        sys.stdout.write(CURSOR_UP_ONE)
        sys.stdout.write(ERASE_LINE)

for x in range(1, 3):
    delete_last_printed_lines(3)

    print('')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)

But it is working not very well, it "move" console window and remove run command.

Is there is any way to fix it? If it will be Python 3+ only solution it is ok.

Upvotes: 0

Views: 935

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

An Unbutu solution would be to call reset:

for x in range(1, 3):
    subprocess.call('reset')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)

Upvotes: 0

labzus
labzus

Reputation: 137

You can use subprocess :

# -*- coding: utf-8 -*-
import sys
import subprocess
from time import sleep

for x in range(1, 3):
    subprocess.call('clear')
    print('')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)

Upvotes: 1

Related Questions