コード例 #1
0
def main():
    table = Table(5, 5)
    robot = Robot(table)
    interpreter = CmdInt(robot)

    while (True):
        interpreter.execute(input("Enter command!\n"))
コード例 #2
0
ファイル: yottu.py プロジェクト: yottu/yottu
def main(argv):
	def __call__(self):
		pass

	dlog = DebugLog("debug.log")
	dlog.msg("Logging started\n")
	
	stdscr = curses.initscr()
	curses.noecho()
	curses.cbreak()
	stdscr.keypad(1)
	curses.start_color()
	
	try:
		wl = WindowLogic(stdscr)
		wl.start()

		ci = CommandInterpreter(stdscr, wl)
		ci.start()
	except Exception as e:
		dlog.excpt(e)
		raise

	ci.join()
	dlog.msg("Command Interpreter joined.\n")
	wl.stop()
	wl.join()
	dlog.msg("Thread Fetcher joined.\n")

	curses.nocbreak()
	stdscr.keypad(0)
	curses.echo()
	curses.endwin()
	curses.resetty()
	dlog.msg("Terminal restored.\n")
コード例 #3
0
ファイル: Shell.py プロジェクト: idle-code/ContextShell
    def __init__(self, root: Node):
        from CommandParser import CommandParser
        from CommandInterpreter import CommandInterpreter
        self._root = root
        self.interpreter = CommandInterpreter(self._root)
        self.parser = CommandParser()

        self.current_path = NodePath()
        self.current_path.is_absolute = True
コード例 #4
0
    def setUp(self):
        self.root = Node()
        self.interpreter = CommandInterpreter(self.root)

        self.root.append_node("foo", Node(1))
        self.root['foo'].append_node("bar", Node(2))
        self.root.append_node("spam", Node('test'))

        # Create 'get' and 'set' actions just for 'foo' branch
        self.root['foo'].append_node(self.interpreter.actions_branch_path,
                                     Node())
        foo_actions = self.root['foo'][self.interpreter.actions_branch_path]
        foo_actions.append_node('get', GetAction())
        foo_actions.append_node('set', SetAction())
コード例 #5
0
ファイル: Shell.py プロジェクト: idle-code/ContextShell
class Shell:
    """Makes interaction with user painless"""
    def __init__(self, root: Node):
        from CommandParser import CommandParser
        from CommandInterpreter import CommandInterpreter
        self._root = root
        self.interpreter = CommandInterpreter(self._root)
        self.parser = CommandParser()

        self.current_path = NodePath()
        self.current_path.is_absolute = True

    def execute(self, command_line: str):
        command = self.parser.parse(command_line)
        if command is None:
            return None
        return self.interpreter.execute(command)

    @staticmethod
    def pretty_print(result):
        if isinstance(result, list):
            for r in result:
                if isinstance(r, Node):
                    print("[{}] {}\t = {}".format(r['@index'], r["@name"], r))
                else:
                    print("[{}] {}".format(r['@index'], r))
        else:
            print(result)
コード例 #6
0
ファイル: Test.py プロジェクト: nebulak/Creatures
    def milestone2(self):
        """ tests Milestone 2

        """ 
        world = World(79, 29, 6, 12, 7, 25)
        world_controller = WorldController(world)
        command_interpreter = CommandInterpreter(world_controller)
        command_interpreter.spawn(20, "Corn", world_controller)
        print("initial World with 20 Corn objects")
        world_controller.printWorld()
        print("cumputing 30 lifecycles")
        print("new world after 30 lifecycles")
        cycle_rounds = 30
        for i in range(0, cycle_rounds):
            world_controller.computeLifeCycle()
        world_controller.printWorld()
コード例 #7
0
def main(argv):
    def __call__(self):
        pass

    stdscr = curses.initscr()
    curses.noecho()  # @UndefinedVariable
    curses.cbreak()  # @UndefinedVariable
    stdscr.keypad(1)
    curses.start_color()

    try:
        wl = WindowLogic(stdscr)
        #wl.start()
    except Exception as e:
        raise

    try:
        dlog = wl.dlog
        dlog.msg("Logging debug output to " + str(dlog.outputFile))
        dlog.msg("Images will be cached in " +
                 wl.cfg.get('file.image.directory'))

        ci = CommandInterpreter(stdscr, wl)
        ci.start()

        updater = Updater(stdscr, wl)
        updater.start()
    except Exception as e:
        dlog.excpt(e)
        raise

    ci.join()
    dlog.msg("Command Interpreter joined.")
    updater.stop()
    updater.join()
    dlog.msg("Updater joined.")
    #wl.stop()
    #wl.join()
    dlog.msg("Thread Fetcher joined.")

    curses.nocbreak()  # @UndefinedVariable
    stdscr.keypad(0)
    curses.echo()  # @UndefinedVariable
    curses.endwin()  # @UndefinedVariable
    curses.resetty()  # @UndefinedVariable
    dlog.msg("Terminal restored.")
コード例 #8
0
        return date.fromtimestamp(time.time()).isoformat()

    def create_file(self, path):
        # Append to a progress file or create if it doesn't exist
        try:
            if os.path.isfile(path):
                return open(path, "a")
            else:
                return open(path, "w+")
        except IOError:
            print("Something went wrong with the file.")


# Our initial shovel
shv = GameObject("objects/shovel.tobj")
shv.set_initial_status(-1, -1, 1)
# Setting the Game up
# Create a new Player
player = Player(-1)
player.add_item(shv)
ci = CommandInterpreter(player, "scenarios/barn.txt")

# Create our Game and supply it with the location of the starting scenario
game = Game(ci)

# Keep going until the 'exit' command is sent
on = True
while on:
    # on is set to false when 'exit' is entered by the user
    on = ci.update(input(ci.get_challenge_text()))
コード例 #9
0
arm = Arm(servoNumber, pulseWidths, initialAngles)

GPIO.setmode(GPIO.BCM)

connectionAvailablePin = 20
GPIO.setup(connectionAvailablePin, GPIO.OUT)

leftMotorPWMPin = 12
leftMotorDirectionPin = 5
rightMotorPWMPin = 13
rightMotorDirectionPin = 6
leftMotor = Motor(leftMotorPWMPin, leftMotorDirectionPin)
rightMotor = Motor(rightMotorPWMPin, rightMotorDirectionPin)
mobilePlatform = MobilePlatform(leftMotor, rightMotor)

commandInterpreter = CommandInterpreter(bluetoothConnection, arm,
                                        mobilePlatform)


def shutdown():
    cleanup()
    subprocess.call("sudo shutdown -h now", shell=True)


def cleanup():
    bluetoothConnection.close()
    mobilePlatform.stop()
    GPIO.cleanup()


try:
    shutdownReceived = False
コード例 #10
0
ファイル: main.py プロジェクト: nebulak/Creatures
"""Starts the Simulation.

Creates a World-, WorldController- and CommandInterpreter Object. Gets User\
input and calls CommandInterpreter.unteroret_command() with it.

"""

from CommandInterpreter import CommandInterpreter
from World import World
from WorldController import WorldController
from copy import copy
from random import random
from Corn import Corn

# main

world = World(79, 29, 6, 12, 7, 25)
world_controller = WorldController(world)
command_interpreter = CommandInterpreter(world_controller)

runProgram = True
world_controller.printWorld()

while(runProgram):
	input_string = input("Enter command <h> for help, <Return> for next cycle)\
                             >>")
	runProgram = command_interpreter.interpret_command(input_string)
コード例 #11
0
    def run(self):
        try:
            self.type = SocketTools.receive(self.socket)[0]
            if self.type == 'client':
                self.mac_address = SocketTools.receive(self.socket)[0]
                try:
                    CommandInterpreter.data['%s_media' % self.mac_address]
                    CommandInterpreter.data['%s_timetable' % self.mac_address]
                    CommandInterpreter.data['%s_name' % self.mac_address]
                    CommandInterpreter.data['%s_should_update' %
                                            self.mac_address]
                except KeyError:
                    CommandInterpreter.data[
                        '%s_media' % self.mac_address] = 'Media/default.mp4'
                    CommandInterpreter.data['%s_timetable' %
                                            self.mac_address] = '07:00,22:00'
                    CommandInterpreter.data['%s_name' %
                                            self.mac_address] = 'default_name'
                    CommandInterpreter.data['%s_should_update' %
                                            self.mac_address] = 'True'
                    CommandInterpreter.interpret('save', self.socket)

                try:
                    with open(
                            CommandInterpreter.data['%s_media' %
                                                    self.mac_address],
                            'rb') as media_file:
                        media_data = media_file.read()
                except FileNotFoundError:
                    if CommandInterpreter.data[
                            '%s_media' %
                            self.mac_address] == 'Media/default.mp4':
                        print('[E] Critical Error : Default Media Missing')
                        sys.exit(-1)
                    else:
                        with open('Media/default.mp4', 'rb') as media_file:
                            media_data = media_file.read()

                SocketTools.send(self.socket, media_data)

                while True:
                    message, message_type = SocketTools.receive(self.socket,
                                                                timeout=None)
                    # print(message, message_type)
                    CommandInterpreter.interpret(message, self.socket)
            elif self.type == 'management':
                print('Manager Connected')
                with open('devices.json', 'r') as json_file:
                    devices = json.load(json_file)
                SocketTools.send(self.socket, devices)

                while True:
                    message, message_type = SocketTools.receive(self.socket,
                                                                timeout=None)
                    print(message, message_type)
                    CommandInterpreter.interpret(message, self.socket)

        except SocketTools.DisconnectError:
            print('[-] Killing Thread For (%s:%s)' % self.address)
            CommandInterpreter.interpret('set %s_online False' %
                                         self.mac_address,
                                         self.socket,
                                         send=False)
            CommandInterpreter.interpret('set %s_should_update True' %
                                         self.mac_address,
                                         self.socket,
                                         send=False)
            self.socket.shutdown(2)
            self.socket.close()
コード例 #12
0
        except SocketTools.DisconnectError:
            print('[-] Killing Thread For (%s:%s)' % self.address)
            CommandInterpreter.interpret('set %s_online False' %
                                         self.mac_address,
                                         self.socket,
                                         send=False)
            CommandInterpreter.interpret('set %s_should_update True' %
                                         self.mac_address,
                                         self.socket,
                                         send=False)
            self.socket.shutdown(2)
            self.socket.close()


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', 12345))
server_socket.listen(5)
server_socket.settimeout(None)

with open('data.json', 'r') as json_file:
    try:
        data = json.load(json_file)
    except json.decoder.JSONDecodeError:
        data = {}
CommandInterpreter.set_data(data)

while True:
    conn, address = server_socket.accept()
    client_thread = ClientThread(conn, address)
    client_thread.start()
コード例 #13
0
class CommandInterpreterTests(unittest.TestCase):
    def setUp(self):
        self.root = Node()
        self.interpreter = CommandInterpreter(self.root)

        self.root.append_node("foo", Node(1))
        self.root['foo'].append_node("bar", Node(2))
        self.root.append_node("spam", Node('test'))

        # Create 'get' and 'set' actions just for 'foo' branch
        self.root['foo'].append_node(self.interpreter.actions_branch_path,
                                     Node())
        foo_actions = self.root['foo'][self.interpreter.actions_branch_path]
        foo_actions.append_node('get', GetAction())
        foo_actions.append_node('set', SetAction())

    def test_find_action(self):
        from_root_node = self.interpreter.find_action(self.interpreter.root,
                                                      'get')
        self.assertIsNone(from_root_node)

        from_foo_node = self.interpreter.find_action(
            self.interpreter.root['foo'], 'get')
        foo = self.root['foo']
        foo_actions = foo[self.interpreter.actions_branch_path]
        foo_actions_get = foo_actions['get']
        self.assertIs(from_foo_node, foo_actions_get)

        from_bar_node = self.interpreter.find_action(
            self.interpreter.root['foo.bar'], 'get')
        self.assertIs(from_bar_node, from_foo_node)

    def test_execute_get(self):
        get_cmd = Command('get')
        get_cmd.target = 'foo'
        foo_val = self.interpreter.execute(get_cmd)
        self.assertEqual(1, foo_val)

        get_cmd.target = 'foo.bar'
        bar_val = self.interpreter.execute(get_cmd)
        self.assertEqual(2, bar_val)

        get_cmd.target = 'spam'
        with self.assertRaises(NameError):
            self.interpreter.execute(get_cmd)

    def test_execute_set(self):
        set_cmd = Command('set')
        set_cmd.target = 'foo'
        set_cmd.arguments = [3]
        self.assertEqual(1, self.interpreter.root['foo'].value)
        self.interpreter.execute(set_cmd)
        self.assertEqual(3, self.interpreter.root['foo'].value)

        self.assertEqual(2, self.interpreter.root['foo.bar'].value)
        set_cmd.target = 'foo.bar'
        self.interpreter.execute(set_cmd)
        self.assertEqual(3, self.interpreter.root['foo.bar'].value)

    def test_unknown_target(self):
        get_cmd = Command('get')
        get_cmd.target = 'rabarbar'
        with self.assertRaises(NameError):
            self.interpreter.execute(get_cmd)

    def test_unknown_action(self):
        unknown_cmd = Command('unknown')
        with self.assertRaises(NameError):
            self.interpreter.execute(unknown_cmd)

    def test_recursive_target_evaluation(self):
        self.root['foo'].append_node('name', Node('foo'))
        # TODO: check why following doesnt't work:
        # self.root.append_node('foo.name', Node('foo'))

        get_name_cmd = Command('get')
        get_name_cmd.target = 'foo.name'

        get_cmd = Command('get')
        get_cmd.target = get_name_cmd

        # Execute: {foo.name: get}: get
        foo_val = self.interpreter.execute(get_cmd)
        self.assertEqual(foo_val, self.root['foo'].value)

    def test_recursive_action_evaluation(self):
        self.root['foo'].append_node('action', Node('get'))

        get_action_cmd = Command('get')
        get_action_cmd.target = 'foo.action'
        get_cmd = Command(get_action_cmd)
        get_cmd.target = 'foo'

        # Execute: foo: {foo.action: get}
        foo_val = self.interpreter.execute(get_cmd)
        self.assertEqual(foo_val, self.root['foo'].value)

    def test_recursive_argument_evaluation(self):
        self.root['foo'].append_node('value', Node(123))

        get_value_cmd = Command('get')
        get_value_cmd.target = 'foo.value'

        set_cmd = Command('set')
        set_cmd.target = 'foo'
        set_cmd.arguments = [get_value_cmd]

        # Execute: foo: set {foo.value: get}
        self.interpreter.execute(set_cmd)
        self.assertEqual(123, self.root['foo'].value)