2

I am looking for a simple way to clear the terminal scrollback from within a Python script. I am aware of os.system('clear'), however this only prints new lines, hiding the scrollback history from view, not deleting it. Is there a way to do this? Thanks!

200_success
  • 7,286
  • 1
  • 43
  • 74
James Lemieux
  • 720
  • 1
  • 9
  • 26

2 Answers2

4

Use the following in Python 2:

>>> print '\033c',

and the following in Python 3:

>>> print('\033c', end=None)

These statements output Escc, which is the VT100 escape sequence for "Reset Device".

200_success
  • 7,286
  • 1
  • 43
  • 74
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • 1
    @James from a shell you should use `echo`, but when using `os.system()`, that messes it up slightly, so `printf` is used here instead. – A.J. Uppal Apr 27 '15 at 05:19
  • 2
    `os.system("printf ...")` is highly, highly redundant: it spawns a shell process just to print something to stdout! You can just use `print` from within Python: `print('\033\143')` – Dietrich Epp Apr 27 '15 at 05:23
  • Seems more streamline. However, I did notice your method leaves a newline, as the `printf` method does not. I am not sure of the cause of this though... Possibly the newline at the end of `print`? – James Lemieux Apr 27 '15 at 05:29
  • 1
    For Python 3, `print('\033\143', end='')`. For Python 2, you get the ugly `print '\033\143',` (notice the trailing comma). – Dietrich Epp Apr 27 '15 at 05:34
  • Actually (that link is not recommended - see [ncurses FAQ](http://invisible-island.net/ncurses/ncurses.faq.html#vt100_color)), the control sequence is usually given as "Full Reset (RIS)" – Thomas Dickey Apr 27 '15 at 08:35
1

As noted, one can use a hardware reset on the terminal, i.e., \033c. That works, but even for a terminal emulator can have some unwanted effects such as resetting colors.

If you were using xterm, that has a specific control sequence \033[3J which does this (see XTerm Control Sequences, i.e., "Ps = 3 -> Erase Saved Lines (xterm)."). OSX Terminal apparently does not implement that, as noted below.

For OSX-specific behavior, this question was asked before, e.g.,

(I have tested the last, and it works for me).

Community
  • 1
  • 1
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • Hmm, looking into `\033[3J` a bit more, I found that `printf '\e[3J'` clears scrollback as well. Any best out of all 3 methods? @Dietrich @A.J. – James Lemieux Apr 28 '15 at 00:41
  • 1
    `\e` is a bashism for `\033` (but as noted, since it did not work on my Mac, it may not work for all). – Thomas Dickey Apr 28 '15 at 00:44