且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有EOFError的python中发生线程的情况下获取用户输入?

更新时间:2022-11-03 19:59:49

根据您的描述,看起来像:我想要一个线程从我用random.randint()替换的服务器上获取数据,我希望一个线程在另一个线程不断检查数据的同时却获得输入.您真正想要使用的是多线程,但是在您的代码中您正在创建并执行2个新流程,而不是2个新线程.因此,如果要使用的是多线程,请执行以下操作,用多线程代替多处理:

Looks like, according to your description: I want one thread that gets data from a server that I have replaced with the random.randint(), and I want one thread that, while the otherone is constantly checking for the data, is getting an input. what you really want to use is multi-threading, but in your code your are creating and executing 2 new Processes, instead of 2 new Threads. So, if what you want to use is multi-threading, do the following instead, replacing the use of multi-processing by the use of multi-threading:

from queue import Queue
import threading
import time
from reprint import output
import time
import random


def receiveThread(queue):
    while True:
        queue.put(random.randint(0, 50))
        time.sleep(0.5)


def sendThread(queue):
    while True:
        queue.put(input())


if __name__ == "__main__":
    send_queue = Queue()
    receive_queue = Queue()

    send_thread = threading.Thread(target=sendThread, daemon=True, args=(send_queue,))
    receive_thread = threading.Thread(target=receiveThread, daemon=True,  args=(receive_queue,))
    receive_thread.start()
    send_thread.start()

    with output(initial_len=2, interval=0) as output_lines:
        while True:
            output_lines[0] = "Received:  {}".format(str(receive_queue.get()))
            output_lines[1] = "Last Sent: {}".format(str(send_queue.get()))
            #output_lines[2] = "Input: {}".format() i don't know how
            #also storing the data in a file but that's irrelevant for here

queue.Queue的实例是线程安全的,因此可以像代码中一样,由多线程代码安全地使用它们.

The instances of queue.Queue are thread-safe, so they can safely be used by multi-thread code, like in the code.