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)
但显然正如预期的那样,当用户继续键入时,输出行与输入行合并。
有任何想法吗?
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |