首页 > 解决方案 > 如何在命令提示符下下推当前行中打印的文本?(Windows 上的 Python 3.8)

问题描述

考虑到以下程序:

from time import sleep
from threading import Thread


def speaker():
    while True:
        sleep(3)
        print("[*]I'm speaking........")


if __name__ == "__main__":
    my_speaker = Thread(target=speaker)
    my_speaker.start()
    while True:
        msg = input("[Your message]>> ")
        print("Your message: " + msg)

如果我没有在输入中输入任何内容('_' 是光标的位置),则输出:

[Your message]>> [*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
_

我想显示的输出:

[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[*]I'm speaking........
[Your message]>> _

当 'speaker' 函数执行打印函数时,它应该执行以下步骤:

我在这里看了一下:https ://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences 我发现了一些有用的东西,比如能够回到当前行的开头使用' \r ',但是我不想覆盖文本,而是将其移动到下一行。

有什么想法?

标签: pythonmultithreadingansi-escape

解决方案


尝试这个:

from time import sleep
from threading import Thread


def speaker():
    while True:
        sleep(3)
        print("\r[*]I'm speaking........\n[Your message]>> ", end="")


if __name__ == "__main__":
    my_speaker = Thread(target=speaker)
    my_speaker.start()
    while True:
        msg = input("[Your message]>> ")
        print("Your message: " + msg)

推荐阅读