【发布时间】:2021-03-07 17:30:55
【问题描述】:
基本上,我有 2 个线程,接收和发送。我希望能够输入一条消息,每当我收到一条新消息时,它就会“打印在我正在输入的行上方”。首先是我认为可行的方法,您只需粘贴它即可运行:
import multiprocessing
import time
from reprint import output
import time
import random
import sys
def receiveThread(queue):
i = 0
while True:
queue.put(i)
i+=1
time.sleep(0.5)
def sendThread(queue):
while True:
a = sys.stdin.read(1)
if (a != ""):
queue.put(a)
if __name__ == "__main__":
send_queue = multiprocessing.Queue()
receive_queue = multiprocessing.Queue()
send_thread = multiprocessing.Process(target=sendThread, args=[send_queue],)
receive_thread = multiprocessing.Process(target=receiveThread, 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()))
但是这里发生的是我无法发送数据。与我输入 a = input() 时不同,输入不会给我一个 EOF,但它会覆盖我在该行中输入的任何内容,所以我如何在一个线程中等待输入而另一个线程工作?
预期行为:
第一行已收到:0、1、2、3、4...
第二行是[我的输入直到我按下回车,然后是我的输入]
如果我不检查 if input != "" 的实际行为
第一行正如预期的那样,只是输入覆盖了前几个字母,直到它重置为 Received
第二行总是空的,也许 bc stdin 只填充了一次我按回车然后总是返回空?
如果我检查if input != "",实际行为
第一行停留:received = 0
第二行就像我输入的任何内容一样,如果我按下回车键,它会进入一个新行,然后我输入内容
【问题讨论】:
-
s是什么?是插座吗?您使用的是什么库/包? -
@MaritnGe 请阅读How to Ask并提供minimal reproducible example
-
请将您的问题edit 提供给minimal reproducible example。请注意,您不是在使用线程,而是在使用进程。后面的错误还表明您的问题是从标准输入读取,而不是线程/进程或套接字。
-
请注意此问题的当前迭代存在语法错误。即使没有,它实际上也没有产生任何输出;两个队列只是无限地积累数据,直到内存耗尽。
-
这是一个通用的 I/O 事情,并不特定于 Python。阅读
stdin/stdoutstandard streams 并从那里开始工作可能会有所帮助。老实说,这并不是最适合初学者的话题。
标签: python input command-line-interface python-multiprocessing