python实现对终端信息的清屏或者部分行清除

有些时候我们看到部分工具能够在给出提示项或者下载库信息的时候,有点类似滚动的效果,其实就是清除了一些行的字符信息。虽然我总结的不是很全,但是就我知道的方式而言,总结了下面的一些方法实现工具,仅供参考:

1. 清全屏

1.1 第三方库

from prompt_toolkit.shortcuts import clear

# 清屏
clear()

1.2 自己实现

import sys


def clear_console():
    # 这个会将整个缓存行全部清理,鼠标无法下滑显示上方的内容
    # sys.stdout.write("\033[2J\033[3J\033[H")    # 改动版本

    # 这个就单纯是清屏,但是不同终端表现有点不同,vscode下的终端可以达到清理的效果,
    # 鼠标滑动,没有历史遗留;但是mac终端或者其他终端显示,只是将上方内容向上做了隐藏
    # 鼠标滑动,还能看到原先的内容
    sys.stdout.write("\033[2J\033[H")

2. 清除部分行

ANSI码的参考: https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797

import sys


def clear_lines(num_lines: int):
	"""这个是先将鼠标上移动 `num_lines` 行, 然后再清除 `num_lines` 行的"""
    # Move the cursor up 'num_lines' lines
    sys.stdout.write("\033[{}A".format(num_lines))
    # Clear the lines
    sys.stdout.write("\033[2K" * num_lines)
    # Move the cursor back to the beginning of the first cleared line
    sys.stdout.write("\033[{}G".format(0))
    sys.stdout.flush()


def clear_lines_from_b_to_u(num_lines: int):
	"""从下往上清除行, 效果更好一些"""
    for _i in range(num_lines, -1, -1):
        # Move the cursor up 'num_lines' lines
        sys.stdout.write("\033[1A")
        # Clear the lines
        sys.stdout.write("\033[2K")
    # Move the cursor back to the beginning of the first cleared line
    sys.stdout.write("\033[{}G".format(0))

以上方式都可以实现对终端字符的清理,同时参考上面的那个 ANSI 码的链接,你还可以自定义更多其他功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值