如何在Python3中同时进行并行输入和输出?

Soh*_*aha 5 python shell multithreading python-multithreading python-3.x

我需要设计一个脚本,该脚本使用终端的顶部部分作为输出,其中在无限循环中每秒打印一些行,底部部分不断接受用户输入并在上面的部分中打印它们(在常规周期中)输出)。

换句话说,我需要设计一种外壳。

我尝试使用简单的方法进行多线程处理,如下所示:

#!/usr/bin/python3

from math import acos
from threading import Thread
from random import choice
from time import sleep
from queue import Queue, Empty

commandQueue = Queue()

def outputThreadFunc():
    outputs = ["So this is another output","Yet another output","Is this even working"] # Just for demo
    while True:
        print(choice(outputs))
        try:
            inp = commandQueue.get(timeout=0.1)
            if inp == 'exit':
                return
            else:
                print(inp)
        except Empty:
            pass        
        sleep(1)

def inputThreadFunc():
    while True:
        command = input("> ") # The shell
        if command == 'exit':
            return
        commandQueue.put(command)

# MAIN CODE
outputThread = Thread(target=outputThreadFunc)
inputThread = Thread(target=inputThreadFunc)
outputThread.start()
inputThread.start()
outputThread.join()
inputThread.join()

print("Exit")
Run Code Online (Sandbox Code Playgroud)

但显然正如预期的那样,当用户继续键入时,输出行与输入行合并。

有任何想法吗?

Hap*_*ace 1

最简单的解决方案是使用两个脚本;一个是打印输出的服务器,另一个是将用户的输入发送到服务器的客户端。然后您可以使用标准解决方案,例如tmux在两个窗格中打开两个脚本。