我需要设计一个脚本,该脚本使用终端的顶部作为输出,其中一些行在无限循环中每秒钟后打印一次,而底部部分继续接受用户输入,并在上面的部分(在定期输出中)打印它们
换句话说,我需要设计一种外壳
我尝试了以下幼稚的多线程方法:
#!/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")
但很明显,正如预期的那样,当用户不断键入时,输出行与输入行合并
有什么想法吗
如评论中所述,使用了
curses
库更新
输入和输出使用两个子温
老办法
我已经编辑了您的示例,以使用
getch
而不是input
最简单的解决方案是使用两个脚本;一个是打印输出的服务器,另一个是向服务器发送用户输入的客户端。然后,您可以使用像
tmux
这样的标准解决方案在两个窗格中打开这两个脚本由于终端写入输出的方式,两者正在合并。它在缓冲区中收集输出,当时间合适时,它会立即输出所有内容。一个简单的解决方法是在每个实际语句之前使用
'\n'
,这样每个新输出都位于单独的行上请注意,由于两个线程并行运行,下一个输出将在您完成键入并按enter键输入之前打印(除非您可以非常快速地键入并具有非常快速的反射)。希望这能回答你的问题
相关问题 更多 >
编程相关推荐