【发布时间】:2021-05-27 18:11:13
【问题描述】:
我需要设计一个脚本,它使用终端的顶部作为输出,其中在无限循环中每秒打印一些行,底部不断接受用户输入并在上面的部分中打印它们(在定期输出)。
换句话说,我需要设计一种外壳。
我尝试使用这样的幼稚方法进行多线程:
#!/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")
但正如预期的那样,随着用户不断输入,输出行与输入行合并。
有什么想法吗?
【问题讨论】:
-
使用 tkinter 设计您的 UI - 在底部输入,在顶部输出。
-
Any ideas?- 这个问题似乎没有最佳答案。 -
ncurses 怎么样?允许吗?
标签: python python-3.x multithreading shell python-multithreading