def test_robot_movement(self): command = CommandParser( 'PLACE 0,0,NORTH MOVE REPORT').get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 0,1,NORTH', self.robot.get_report_state()) command = CommandParser( 'PLACE 0,0,NORTH LEFT REPORT').get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 0,0,WEST', self.robot.get_report_state()) command = CommandParser('PLACE 1,2,EAST MOVE MOVE LEFT MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 3,3,NORTH', self.robot.get_report_state()) command = CommandParser('PLACE 0,0,EAST MOVE MOVE LEFT MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 2,1,NORTH', self.robot.get_report_state()) command = CommandParser( 'PLACE 0,0,EAST MOVE MOVE LEFT MOVE PLACE 3,3,SOUTH MOVE REPORT' ).get_validated_command() self.robot.robot_movemant(command) self.assertEqual('Output: 3,2,SOUTH', self.robot.get_report_state())
def create_command_parser(): command_parser = CommandParser() command_parser.add_command('show_movies', show_movies) command_parser.add_command('show_movie_projections', show_movie_projections) command_parser.add_command('make_reservation', make_reservation) command_parser.add_command('cancel_reservation', cancel_reservation) command_parser.add_command('exit', exit) command_parser.add_command('help', show_help) return command_parser
def main(): parser = CommandParser() try: command_list = parser.parse() except CommandParser.ParserException as e: sys.exit(e) router = Router(command_list) runner_class = router.get_runner() timeline = Timeline() runner_class(timeline).run(command_list)
def main(): engine = create_engine("sqlite:///cinema.db") Base.metadata.create_all(engine) session = Session(bind=engine) cinema_city = Cinema(session) new_movies_and_projections_in_cinema(cinema_city) command_parser = CommandParser() command_parser.add_command("show_movies", cinema_city.show_movies) cinema_city.show_movies(session) command = input(">>>") command_parser.run_command(command)
def Initialize(port, functionMap={}, asyncHandler=None): ''' Initializes BlackBoard with the corresponding parameters. :param int port: The port through which BlackBoard will communicate with this module. :param dictionary functionMap: A dictionary containing **key:value** pairs, where the *key* is the name of a command received (a string), and the *value* is either a tuple containing a function as a first element and a boolean as a second element, or a function. The function in both cases is the function that is going to execute the specified command and receives on object of type :class:`Command` (See :ref:`Creating a command handler <creating_a_command_handler>`). The boolean value indicates whether the execution of that command should be synchronous (on the same thread) or asynchronous, usually synchronous execution is preferred for fast commands that can answer almost immediately and asynchronous for commands that might take a little time. When the value is only a function, by default the execution is synchronous. *functionMap* can also contain an entry with a string containing only an asterisk, meaning that would be the handler in case no other handler is found for a specific command. .. note:: Notice that although functionMap can include a wildcard handler and this might seem like the module could answer anything, BlackBoard will only send commands that are registered under this module's configuration. :param function asyncHandler: A function that would handle the response of commands when sent with the method :func:`Send` instead of using :func:`SendAndWait`. This means the execution of a program that sends a command could continue and an asynchronous handler would handle the response when one is received. .. note:: Notice that the asyncHandler functionality could also be achieved using a :class:`ParallelSender` object, but it has other implications. ''' global _executors, _connMan, _parser, _p, _initialized, _ready _executors = { 'busy': (lambda x: Response('busy'), False), 'ready': (_isReady, False), 'alive': (lambda x: Response('alive', True), False) } for m in functionMap: if isinstance(functionMap[m], types.FunctionType): _executors[m] = (functionMap[m], False) elif isinstance(functionMap[m], tuple): _executors[m] = functionMap[m] else: print 'Element in function map is not a function nor a correct tuple: ' + repr( functionMap[m]) _connMan = ConnectionManager(port) _parser = CommandParser(asyncHandler) _p = threading.Thread(target=_MainThread) _p.daemon = True _initialized = True
def main(): fill_with_questions(session) command_parser = CommandParser() command_parser.add_command("begin", begin_interaction_with_user) command_parser.add_command("start", start_game) command_parser.add_command("highscores", show_highscores) command_parser.add_command("finish", finish) command_parser.run_command("begin") command = prompt_for_input() command_parser.run_command(command) while command != "finish": command = prompt_for_input() command_parser.run_command(command)
def __init__(self, test_name): # Only argument stuff self.running = False self.bt_receiver = btReceiver(debug = True) self.file_manager = fileManager(test_name, debug = True) self.command_parser = CommandParser() self.rotation = Rotation() self.mode = "manual" self.control_mode = "torque" self.attitude = [0,0,0] #[ypr] [DEG] self.speed = [HDD_ZERO_SPEED,HDD_ZERO_SPEED,HDD_ZERO_SPEED] #[xyz] [RPM] self.torque = [0,0,0] #[xyz] [Nm] self.voltage = [0,0,0] #[xyz] [V] self.iGains = [5, 10, 0] #[PID] self.wGains = [15, 25, 0] #[PID]
def __init__(self, queue_read: Queue, queue_sent: Queue): super().__init__() self.queue_read = queue_read self.queue_sent = queue_sent # queue_read Timer initialization self.queue_timer = QTimer(self) self.queue_timer.timeout.connect(self.queueChecker) # Better to use gui/qt for timer functionality to operate with qt inside qt self.queue_timer.setInterval( 10) # each 10ms call func to check queue messages from websocket self.queue_timer.start() # Init command parse self.cmd_parser = CommandParser() # Create communication protocol self.protocol = ClientProtocol()
def __init__(self, args): self.no_colors = False def parse_args_and_opts(args): optionParser = OptionParser() for opt in Todo.opts: optionParser.add_option(*opt[4:], help=opt[0], action=opt[1], dest=opt[2], default=opt[3]) return optionParser.parse_args() if not os.path.exists(os.path.dirname(_todo_file)): os.mkdir(os.path.dirname(_todo_file)) if not os.path.exists(_todo_file): with file(_todo_file, 'w') as f: pass try: opts, args = parse_args_and_opts(args) setattr(Todo, 'no_colors', opts.no_colors) parserGenerator = TaskParserGenerator(_todo_file) tasks, last_index = parserGenerator.parse() commandParser = CommandParser([cmd[1] for cmd in Todo.cmds]) command, args_left = commandParser.parse(args) changes = getattr(Todo.TodoCommands(tasks, last_index), command)(args_left) if changes: parserGenerator.generate(tasks) except (TodoError, IOError, ValueError) as err: print('error: {0}'.format(err))
def start(self): """ Makes all required initializations and starts the server. """ print "Starting AWG server..." print "Listening on %s" % (self.host) print "RPCBIND on port %s" % (self.rpcbind_port) print "VXI-11 on port %s" % (self.vxi11_port) print "Creating sockets..." # Create RPCBIND socket self.rpcbind_socket = self.create_socket(self.host, self.rpcbind_port) # Create VXI-11 socket self.lxi_socket = self.create_socket(self.host, self.vxi11_port) # Initialize SCPI command parser self.parser = CommandParser(self.awg) # Connect to the external AWG #self.awg.initialize() # Run the server self.main_loop()
""" Handlers for the RPG commands. """ import guilds from guilds import guilds_instance from . import rpg_instance from command_parser import CommandParser import time parser = CommandParser("?") parser.add_custom_context( "player", lambda ctx: rpg_instance.fetchplayer(ctx.user.id, ctx.user.name)) @parser.command(aliases="h", help_text="show this help message") async def help(ctx): response = "**Commands:**\n" for command in parser.commands: help_text = parser.get_command_help(command) if help_text is not None: response += "\n" + help_text await ctx.send(response) """ SPAM COOLDOWN TRACKER - user id keys, time.time() values """ cooldowns = {}
#!/usr/bin/env python3 # `cpp_tools` is a set of lightweight python scripts used to facilitate and speed up development in C++. # Copyright (C) 2018 Guillaume Duclos-Cianci # This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later # version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program. # If not, see <http://www.gnu.org/licenses/>. from command_create_project import CommandCreateProject from command_parser import CommandParser if __name__ == '__main__': command = CommandParser().parse() command.execute()
def __init__(self): self.command_parser = CommandParser() self.reset()
def setUp(self): self.parser = CommandParser()
from command_parser import CommandParser cp = CommandParser() while True: try: command = input(cp.get_prompt()) cp.breakout(command) except StopIteration: break
def test_known_command(): parser = CommandParser(cmds) result_cmd, result_args = parser.parse([cmds[0]] + args) assert result_cmd == cmds[0] assert result_args == args
def test_unknown_command(): parser = CommandParser(cmds) cmd, _ = parser.parse(['greet'] + args)
def __init__(self): self.game = Game() self.command_parser = CommandParser() self.init_command_parser() print('Welcome to the "Do you even math?" game!')
class NoNickname(Exception): pass def read_token(): token_file_name = os.path.join(WORKDIR, 'fmf_bot_token') if not os.path.isfile(token_file_name): token_file_name = '/root/fmf_bot_token' with open(token_file_name, 'r') as f: return f.read().strip() bot = Bot(token=read_token()) dp = Dispatcher(bot) command_parser = CommandParser(dp) def member_in_db(connection, member_id): cur = connection.cursor() cur.execute('SELECT COUNT(*) FROM members WHERE id=?', (member_id, )) return cur.fetchone()[0] > 0 def add_member_to_db(connection, member_id, member_name, chat_id): cur = connection.cursor() # member_id and chat_id are the same, so it's just a historical issue. cur.execute('INSERT INTO members (id, name, chat) VALUES (?, ?, ?)', (member_id, member_name, chat_id)) connection.commit()
try: color = webcolors.name_to_hex(color_string, spec='css3')[1:] return color except: try: color = color_string[1:] test = webcolors.hex_to_rgb("#" + color) return color except: return False """ GUILD MODULE COMMANDS """ parser = CommandParser("!") parser.add_custom_context( "guild", lambda ctx: guilds_instance.fetch_guild(ctx.message.guild.id)) @parser.command(aliases="h", help_text="show this help message") async def help(ctx): response = "**Commands:**\n" for command in parser.commands: help_text = parser.get_command_help(command) if help_text is not None: response += "\n" + help_text await ctx.send(response) @parser.command(help_text="shows the guild's parties")
from robot import Robot from table import Table from command_parser import CommandParser if __name__ == '__main__': table = Table() robot = Robot(table) input_command = 'init' os.system('cls') print("Toy Robot Simulation\n") input_choice = str( input( 'CHOOSE 1 AUTOMATE TESTING (with ready files) or 2 FOR MANUAL TESTING (input via console) ' )) if input_choice == '1': with open('example_files/commands1.txt') as fp: lines = fp.read().split("\n") for input_command in lines: print("Input: " + input_command) command_parser = CommandParser( input_command).get_validated_command() robot.robot_movemant(command_parser) print("\n") elif input_choice == '2': while input_command: input_command = str(input('Input: ')) command_parser = CommandParser( input_command).get_validated_command() robot.robot_movemant(command_parser)