advanced-python-homework-20.../noblocking_turtle_shell.py

67 lines
1.9 KiB
Python
Raw Permalink Normal View History

2023-11-04 19:05:45 +03:00
import cmd
import threading
2023-11-15 23:29:16 +03:00
from threading import Thread
from threading import Event
2023-11-20 16:17:49 +03:00
import argparse
2023-11-16 23:56:44 +03:00
import time
2023-11-04 19:05:45 +03:00
from queue import Queue
from equipment.turtle_device import TurtleDevice
class TurtleDeviceThread(threading.Thread):
2023-11-15 23:29:16 +03:00
# TODO(Homework 4) \begin
def __message_processing__(self):
while True:
new_message = self.queue.get()
2023-11-20 16:17:49 +03:00
#print(type(new_message))
#print(new_message)
#print("Name and args of action are {}".format(new_message))
self.device.execute(*new_message)
2023-11-16 23:56:44 +03:00
#time.sleep(30)
2023-11-15 23:29:16 +03:00
self.queue.task_done()
if self.event.is_set():
break
def __message_thread__(self):
2023-11-16 23:56:44 +03:00
thread = Thread(target = self.__message_processing__, daemon=True)
2023-11-15 23:29:16 +03:00
thread.start()
# TODO(Homework 4) \end
2023-11-04 19:05:45 +03:00
def __init__(self):
super().__init__()
self.device = TurtleDevice()
self.queue = Queue()
2023-11-15 23:29:16 +03:00
self.event = Event()
2023-11-04 19:05:45 +03:00
class NoBlockingTurtleShell(cmd.Cmd):
intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
prompt = '(turtle) '
file = None
def __init__(self, turtle_thread: TurtleDeviceThread):
2023-11-15 23:29:16 +03:00
# TODO(Homework 4) \begin
2023-11-16 23:56:44 +03:00
super(NoBlockingTurtleShell, self).__init__()
2023-11-15 23:29:16 +03:00
turtle_thread.__message_thread__()
# TODO(Homework 4) \end
2023-11-04 19:05:45 +03:00
def do_execute(self, arg):
2023-11-15 23:29:16 +03:00
# TODO(Homework 4) \begin
2023-11-20 16:17:49 +03:00
turtle_thread.queue.put(parse(arg))
2023-11-15 23:29:16 +03:00
# TODO(Homework 4) \end
2023-11-04 19:05:45 +03:00
def do_exit(self, arg):
2023-11-15 23:29:16 +03:00
# TODO(Homework 4) \begin
turtle_thread.event.set()
# TODO(Homework 4) \end
2023-11-20 16:17:49 +03:00
def parse(arg):
'Convert a series of zero or more numbers to an argument tuple'
return tuple(arg.split())
2023-11-04 19:05:45 +03:00
if __name__ == '__main__':
turtle_thread = TurtleDeviceThread()
# TODO(Homework 4: Correct start thread)
NoBlockingTurtleShell(turtle_thread).cmdloop()