如何将数据添加到标准输出而不覆盖现有数据?

问题描述 投票:0回答:1

我正在尝试实现一个控制台聊天系统。连接后,它应该在 while True 循环中请求 input() ,接收消息并打印它们。工作流程示例:

Received: hello
Receved: there
Enter your message: 

每次收到消息,输入提示都会移动一行。话虽这么说,我想在前面加上{message} 收到消息时输入您的消息。 覆盖标准输出,我想避免这种行为。

示例代码:

import sys

my_words = ['there', 'hello']

for word in my_words:
    sys.stdout.write(f'\r{word} ')

所需输出:

hello there

实际产量:

hello
python python-3.x escaping stdout
1个回答
0
投票

结合使用

'\r'
'\n'

import sys    

i = 1
while True:
    # simulate arrival of message every two cycles
    received_message = None
    if i % 2:
        received_message = "Hi there"
    i += 1

    # this should happen asynchronously, but formatting remains the same
    if received_message:
        sys.stdout.write(f'\rReceived: {received_message}\n')
    sys.stdout.write(f'\rEnter text: ')
    line = sys.stdin.readline()

输出

Received: Hi there
Enter text: first message
Enter text: second
Received: Hi there
Enter text: another message
Enter text: last
Received: Hi there
Enter text: ...
© www.soinside.com 2019 - 2024. All rights reserved.