有些时候我们看到部分工具能够在给出提示项或者下载库信息的时候,有点类似滚动的效果,其实就是清除了一些行的字符信息。虽然我总结的不是很全,但是就我知道的方式而言,总结了下面的一些方法实现工具,仅供参考:
1. 清全屏
1.1 第三方库
from prompt_toolkit.shortcuts import clear# 清屏
clear()
1.2 自己实现
import sysdef 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 sysdef clear_lines(num_lines: int):"""这个是先将鼠标上移动 `num_lines` 行, 然后再清除 `num_lines` 行的"""# Move the cursor up 'num_lines' linessys.stdout.write("\033[{}A".format(num_lines))# Clear the linessys.stdout.write("\033[2K" * num_lines)# Move the cursor back to the beginning of the first cleared linesys.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' linessys.stdout.write("\033[1A")# Clear the linessys.stdout.write("\033[2K")# Move the cursor back to the beginning of the first cleared linesys.stdout.write("\033[{}G".format(0))
以上方式都可以实现对终端字符的清理,同时参考上面的那个 ANSI 码的链接,你还可以自定义更多其他功能。