如图所示,python脚本如何清空之前的输出到光标位置?-灵析社区

M78的社畜

`\r` 可以做到。运行下面代码看看是不是你要的效果: import time for i in range(10): print(f"{i=}", end="\r", flush=True) time.sleep(1) 或者通过ANSI控制字符来控制终端的字符行为: import sys def clear_console(): # 这个会将整个缓存行全部清理,鼠标无法下滑显示上方的内容 # sys.stdout.write("\033[2J\033[3J\033[H") # 改动版本 # 这个就单纯是清屏,但是不同终端表现有点不同,vscode下的终端可以达到清理的效果, # 鼠标滑动,没有历史遗留;但是mac终端或者其他终端显示,只是将上方内容向上做了隐藏 # 鼠标滑动,还能看到原先的内容 sys.stdout.write("\033[2J\033[H") 把这个函数插入到你想使用的地方就可以实现清屏。 * ESC - sequence starting with ESC (\x1B) or (\033) ESC Code Sequence | Description ---|--- ESC[J | erase in display (same as ESC[0J) ESC[0J | erase from cursor until end of screen ESC[1J | erase from cursor to beginning of screen ESC[2J | erase entire screen ESC[3J | erase saved lines ESC[K | erase in line (same as ESC[0K) ESC[0K | erase from cursor to end of line ESC[1K | erase start of line to the cursor ESC[2K | erase the entire line 除此之外,你还可以实现针对行的清除,我曾经有实现过这个逻辑,代码粘贴给你: import sys def clear_lines_(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字符集的资料很多,这里我贴出来一个 [ANSI Escape Sequences](https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797)

阅读量:1

点赞量:0

问AI