我需要设计一个脚本,它使用终端的顶部作为输出,其中一些行在无限循环中每秒打印一次,底部不断接受用户输入并将它们打印在上面的部分(在定期定期输出)。
换句话说,我需要设计一种 shell 。
我用这样的幼稚方法尝试了多线程:
#!/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")
但正如预期的那样,随着用户不断输入,输出行与输入行合并。有任何想法吗?
最佳答案
最简单的解决方案是使用两个脚本;一个是打印输出的服务器,另一个是将用户输入发送到服务器的客户端。然后你可以使用像 tmux
这样的标准解决方案。在两个 Pane 中打开两个脚本。
关于python - 如何在Python3中同时进行并行输入和输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67727755/