Python 等待输入时打印

Python Print while waiting for input

def receivedata(self):
    while True:
        data = self.soc.recv(1024)
        if data != "" or data != '' or data != "":
            sys.stdout.write("Recv>> ")
            sys.stdout.write(data)
            sys.stdout.flush()
            if data == "Server Shutdown":
                self.soc.close()
        elif not data:
            continue
def senddata(self):
    while True:
        try:
            sys.stdout.write("Send>> ")
            msg = sys.stdin.readline()
            self.soc.send(msg)
        except socket.error:
            sys.stdout.write("Socket Connection Timed Out")

这是我的 python 客户端代码的一部分,我希望它在等待用户输入时打印从服务器接收到的内容。

但是,客户端在等待用户输入时不会打印任何内容——它只会在用户输入内容时打印。

有什么方法可以更改它,使其在等待用户输入时也能打印?

如果您的程序需要等待 2 个单独的事件(用户输入和传入的套接字数据),您将不得不使用线程,例如:

recv_thread = threading.Thread(target=receivedata)
recv_thread.setDaemon(True)
recv_thread.start()
senddata()

关于代码的一些事情:

  • 当遇到socket.error时,它可能不是超时。
  • 在某一时刻,您需要从 senddata 退出 while 循环(当用户输入特定文本时?或)以防出现异常。
  • 还在receivedata
  • 中加入异常处理
  • if receivedata 中的语句不正确。您可以将其替换为:

    if data:
        ...if statements...