我正在用python编写一个小的命令行游戏,其中我使用tqdm模块显示了一个进度条。我使用msvcrt模块监听用户输入,以中断进程。一旦中断,用户可以通过在命令行提示符中输入“restart”来重新启动。第二次显示进度条时,它不是用进度更新同一行,而是每次创建一个新行。
我怎么才能让它显示同一条线上的进展呢?
这段代码演示了我对进度条的使用。
def transfer():
for i in tqdm.tqdm(range(1000), desc="Transfer progress", ncols=100, bar_format='{l_bar}{bar}|'):
sleep(.1)
if msvcrt.kbhit():
if msvcrt.getwche() == ' ':
interrupt()
break
def interrupt():
type("File transfer interrupted, to restart the transfer, type 'restart'")
这个命令在google colab中有效。
尝试使用
tqdm.tqdm.write
代替标准print()
这将打印在进度条上方,并将进度条移动到下方一行。
我使用下面的代码对此进行了测试,按
space
将打印到stdout中,但不会中断循环。 还不完全清楚您要实现什么,因为您的interrupt()
函数只检查提供的字符串的类型。type() built-in function编辑:包括Paul Netherwood指出的
tqdm.write()
的end
参数 tqdm.tqdm.write()尝试使用
position=0
和leave=True
(解决方案在Google Colab中工作以避免打印到换行符)
相关问题 更多 >
编程相关推荐