advanced-python-homework-2023/turtle/noblocking_turtle_shell.py

74 lines
2.0 KiB
Python
Raw Normal View History

2023-11-04 19:05:45 +03:00
import cmd
import threading
from queue import Queue
from equipment.turtle_device import TurtleDevice
class TurtleDeviceThread(threading.Thread):
# TODO(Homework 4)
def __init__(self):
super().__init__()
self.device = TurtleDevice()
2023-11-16 21:21:10 +03:00
2023-11-10 15:05:58 +03:00
self.queue = Queue[tuple]()
self.device.open()
self.device.execute("speed", 1)
def run(self):
while True:
action, args, kwargs = self.queue.get()
2023-11-16 21:21:10 +03:00
if action == "exit":
self.queue.task_done()
break
2023-11-10 15:05:58 +03:00
self.device.execute(action, *args, **kwargs)
self.queue.task_done()
def add_task(self, action, *args, **kwargs):
self.queue.put((action, args, kwargs))
2023-11-04 19:05:45 +03:00
class NoBlockingTurtleShell(cmd.Cmd):
2023-11-10 15:05:58 +03:00
intro = "Welcome to the turtle shell. Type help or ? to list commands.\n"
prompt = "(turtle) "
2023-11-04 19:05:45 +03:00
file = None
def __init__(self, turtle_thread: TurtleDeviceThread):
2023-11-10 15:05:58 +03:00
super().__init__()
self.turtle_thread = turtle_thread
@property
def turtle_device(self):
return self.turtle_thread.device
2023-11-04 19:05:45 +03:00
def do_execute(self, arg):
2023-11-16 21:21:10 +03:00
command_and_args = arg.split()
if len(command_and_args) == 1:
self.turtle_thread.add_task(command)
return
command = command_and_args[0]
args = tuple(int(c) if c.isdecimal() else c for c in command_and_args[1:])
self.turtle_thread.add_task(command, *args)
2023-11-10 15:05:58 +03:00
2023-11-16 21:21:10 +03:00
def do_fw(self, arg):
self.do_execute("forward 100")
2023-11-10 15:05:58 +03:00
2023-11-16 21:21:10 +03:00
def do_le(self, arg):
self.do_execute("left 1000")
2023-11-10 15:05:58 +03:00
2023-11-16 21:21:10 +03:00
def do_exit(self, arg):
self.turtle_thread.add_task("exit")
return True
2023-11-04 19:05:45 +03:00
2023-11-10 15:05:58 +03:00
if __name__ == "__main__":
2023-11-04 19:05:45 +03:00
turtle_thread = TurtleDeviceThread()
# TODO(Homework 4: Correct start thread)
2023-11-10 15:05:58 +03:00
turtle_thread.daemon = True
2023-11-16 21:21:10 +03:00
thread_shell = threading.Thread(target=NoBlockingTurtleShell(turtle_thread).cmdloop)
thread_shell.start()
turtle_thread.run()
thread_shell.join()