Python - 更优雅地清除终端屏幕 [英] Python - Clearing the terminal screen more elegantly

查看:29
本文介绍了Python - 更优雅地清除终端屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以通过使用 os.system 执行 clear 来清除 shell,但是这种方式对我来说似乎很混乱,因为命令被记录在历史记录中并且是字面上解释为以用户身份运行到操作系统的命令.

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?

推荐答案

print "\033c"

适用于我的系统.

您还可以缓存由 clear 命令生成的清屏转义序列:

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

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

然后

print clear_screen_seq

任何时候你想清屏.

tput clear 命令 产生POSIX 中定义了相同的序列.

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

你可以使用curses,得到序列:

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')

优点是你不需要调用curses.initscr()来获取一个包含.erase()的窗口对象,.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.

要在 Python 2 和 3 上使用相同的源代码,您可以使用 os.write() 函数:

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 命令也尝试使用 tigetstr("E3") 清除回滚缓冲区.

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

这是 clear.c 命令:

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)

这篇关于Python - 更优雅地清除终端屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆