分开输入和打印线程



在等待用户输入时,我只是在摸索如何打印文本。例如,如果我们在聊天应用程序中,我们有一个input(),以便用户在接收消息时发送消息和print()。它需要同时进行。我试着使用线程,但它总是停在一个线程上。

示例:

def receive(client):
threadName = client.getThreadName()
while not client.isStopThread():
time.sleep(1)
print('test')
while (client.isThereMessage()):
print('[' + threadName + ']: ' + client.getMessage())

对于主程序

client.startThread(thread.uid)
receiveThread = Thread(target = receive(client))
receiveThread.deamon = True
receiveThread.start()
while True:
toSendMessage = input('[' + client.fetchThreadInfo(client.uid)[client.uid].name + ']: ')
client.sendMessage(toSendMessage, thread_id=thread.uid, thread_type=thread.type)

您错误地调用了Thread类构造函数。签名为:

threading.Thread(target=None, args=(), kwargs={})

target是函数对象本身,即receive,而不是receive(client)。现在,调用client为输入的receive函数,然后将该函数的返回值(看起来是None)作为target关键字参数传递给Thread构造函数。如果receive函数无限循环,那么代码肯定会在Thread构造函数中停滞。

您应该调用Thread构造函数,如下所示:

receiveThread = Thread(target=receive, args=(client,))

此外,一般来说,您不需要线程来打印内容和等待输入。相反,您可以执行所谓的同步I/O多路复用,这意味着同时从单个线程对多个对象执行I/O。这个想法是当一个或多个对象可用于写入或读取(或两者兼有)时,等待操作系统的通知。有关更多信息,请参阅selectselectors模块。

这里有一个简单的例子。它只需要等待一秒钟,等待用户的输入。如果接收到输入,它只将其回波,如果没有接收到,它将打印Nothing new

import sys
import select
timeout = 1.0
while True:
rlist, _ = select.select([sys.stdin], [], [], timeout)
if len(rlist):
print(sys.stdin.readline())
else:
print('Nothing new')

您可以对此进行调整,以等待用户输入和要打印到用户控制台的新消息。

最新更新