如何在行的开头打印文本而不覆盖现有的输入文本?

时间:2017-11-01 00:31:28

标签: python multithreading python-3.x printing

我一直在尝试用Python创建一个多线程的聊天服务器和客户端,除了一件事,它一切都很顺利。我有两个线程,一个用于发送消息,另一个用于接收和打印消息,如下所示。

class SendThread(threading.Thread):

    def __init__(self):
        super().__init__()

    def run(self):
        global s
        try:
            while s:
                time.sleep(0.2)  
                data = input("\r")
                s.send(data.encode("ASCII"))
        except:
            print("An exception occurred, terminating!")
            s.close()

class RecvThread(threading.Thread):

    def __init__(self):
        super().__init__()

    def run(self):
        global s
        try:
            while s:
                recv = s.recv(4096)
                if recv:
                    print("\r" + recv.decode("ASCII"), flush=True)
                else:
                    s.close()
                    print("You have disconnected from the server!")
        except:
            print("An exception occurred, terminating!")
            s.close()

问题是当一个人正在键入要发送的消息,并且收到另一个连接的客户端发送的消息时,当前输入的消息会消失,但仍然存在,因为它仍然存储。

我想要发生的是收到的信息显示在输入所在的同一行上,然后在它之后打印换行符,以便输入文字显示在下一行:

# before other client(s) send a message

User1: hello!
Me: hi!
how are you?                           # currently being typed

# after other client(s) send a message

User1: hello!
Me: hi!
User1: are you alright?
how are you? good?                     # still being typed

# when the current user sends the message

User1: hello!
Me: hi!
User1: are you alright?
Me: how are you? good?                 # sent message
i'm fine,                              # new input being typed

现在,输出是:

# before other client(s) send a message

User1: hello!
Me: hi!
how are you?                           # currently being typed

# after other client(s) send a message

User1: hello!
Me: hi!
User1: are you alright?
good?                                  # still being typed

# when the current user sends the message

User1: hello!
Me: hi!
User1: are you alright?
Me: how are you? good?                 # sent message
i'm fine,                              # new input being typed

任何帮助将不胜感激。

0 个答案:

没有答案