Python - Clearing the terminal screen more elegantly

谁说胖子不能爱 提交于 2020-01-09 10:59:02

问题


I know you can clear the shell by executing clear using os.system, but this way seems quite messy to me since the commands are logged in the history and are litterally interpreted as commands run as the user to the OS.

I'd like to know if there is a better way to clear the output in a commandline script?


回答1:


print "\033c"

works on my system.

You could also cache the clear-screen escape sequence produced by clear command:

import subprocess
clear_screen_seq = subprocess.check_output('clear')

then

print clear_screen_seq

any time you want to clear the screen.

tput clear command that produces the same sequence is defined in POSIX.

You could use curses, to get the sequence:

import curses
import sys

clear_screen_seq = b''
if sys.stdout.isatty():
    curses.setupterm()
    clear_screen_seq = curses.tigetstr('clear')

The advantage is that you don't need to call curses.initscr() that is required to get a window object which has .erase(), .clear() methods.

To use the same source on both Python 2 and 3, you could use os.write() function:

import os
os.write(sys.stdout.fileno(), clear_screen_seq)

clear command on my system also tries to clear the scrollback buffer using tigetstr("E3").

Here's a complete Python port of the clear.c command:

#!/usr/bin/env python
"""Clear screen in the terminal."""
import curses
import os
import sys

curses.setupterm()
e3 = curses.tigetstr('E3') or b''
clear_screen_seq = curses.tigetstr('clear') or b''
os.write(sys.stdout.fileno(), e3 + clear_screen_seq)



回答2:


You can use the Python interface to ncurses, specifically window.erase and window.clear.

https://docs.python.org/3.5/library/curses.html




回答3:


I use 2 print statements to clear the screen.

Clears the screen:

print(chr(27) + "[2J")

Moves cursor to begining row 1 column 1:

print(chr(27) + "[1;1f")

I like this method because you can move the cursor anywhere you want by [<row>;<col>f

The chr(27) is the escape character and the stuff in quotes tells the terminal what to do.



来源:https://stackoverflow.com/questions/34388390/python-clearing-the-terminal-screen-more-elegantly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!