我正在尝试基本清除控制台行,但不清除整个控制台窗口而不使用空格,以使我没有最后打印的多余字符。例如:
# This causes characters from the last thing printed:
print("I don't know you.", end="\r")
print("Hello Jim!", end="\r")
# Yields the following (without the quotations) -->
# "Hello Jim!ow you."
现在解决这个问题可以做到:
import os
def new_print(message, end):
"""
Clears console, no matter the size of the previous line
without wrapping to a new line
"""
width_of_console = int(os.popen("stty size", "r").read().split()[1])
# = 17
print(f"{message :<{width_of_console}}", end=end)
new_print("I don't know you.", end="\r")
new_print("Hello Jim!", end="\r")
# Yields the following (without the quotations) -->
# "Hello Jim! "
我怎么
"Hello Jim!"
而不是"Hello Jim! "
(显然都没有引号)在将尺寸(例如从控制台宽度从17更改为30)转换为控制台时,在控制台中会发生类似这样的事情,在我看来,这种情况经常发生:
Hello Jim! Hello Jim!
Hello Jim! Hello Jim
! Hello Jim! Hello
Jim! Hello Jim! H
ello Jim! Hello Jim!
我愿意采用一种全新的工作方式,例如使用urwid或类似性质的东西。
答案 0 :(得分:2)
您可以使用EL(擦除线)control sequence。在Python中,最简单的构建方法是:
"\033[2K"
数字控制EL序列的行为:
EL序列不会移动光标。
这种行为是相当标准的,但是如果您想确定的话,可以使用tput
查询terminfo数据库。
tl; dr:
print("I don't know you.", end="\r")
print("\033[2KHello Jim!", end="\r")
答案 1 :(得分:0)
您可以执行以下操作。为了提高可见度,我添加了一个睡眠时间。
import time
def myprint(msg):
print(msg, end='', flush=True)
time.sleep(1)
print('\r', end='', flush=True)
print(' ' * len(msg), end='', flush=True)
print('\r', end='', flush=True)
print('These are some other lines 1')
print('These are some other lines 2')
for i in range(10):
myprint('Hello Jim {}!'.format(i))