Exemplo n.º 1
0
 def test_get_command(self):
     """tests if the get_command method works"""
     command_string = "get filedata"
     # get an existing command
     self.assertEqual(get_command(get_filedata), command_string)
     # get an illegal command
     self.assertEqual(get_command(invalid_function), None)
Exemplo n.º 2
0
	def __handle_request(self, caller):
		"""This is called whenever data is received from one of the client."""
		try:
			data = caller.receive()
			logging.debug("Parsing this data: '" + data + "'")
			result = self.parser.parse(data)
			logging.debug("Result of parsing: '" + result.command_name + "(" + ",".join(result.command_arguments) + ")'")
			cmd = commands.get_command(result.command_name, self, caller, result.command_arguments)
			cmd.execute()
		except commands.ArgumentsValidationError as e:
			#Command arguments did not validate.
			print(e)
			print("asdasdasdasd")
			cmd = commands.get_command("Whisper", self, self.server_client, [caller.name, str(e)])
			cmd.execute()
		except commands.ExecutionFailedError as e:
			#Tell the client that the command could not be executed properly.
			cmd = commands.get_command("Whisper", self, self.server_client, [caller.name, "Command execution failed"])
			cmd.execute()
			logging.exception(e)
		except clients.SocketError as e:
			#Client probably just disconnected.
			logging.debug("SocketError while handling request.")
			logging.exception(e)
			self.disconnect_client(caller)
		except clients.ClientIsNotFinishedSendingError as e:
			#Client has not finished sending it's data.  
			pass
		except NameError as e:
			# The command is not recognized.
			cmd = commands.get_command("Whisper", self, self.server_client, [caller.name, "Unrecognized command"])
			cmd.execute()
Exemplo n.º 3
0
 def test_get_command(self):
     """tests if the get_command method works"""
     command_string = "get filedata"
     # get an existing command
     self.assertEqual(get_command(get_filedata),
                      command_string)
     # get an illegal command
     self.assertEqual(get_command(invalid_function), None)
Exemplo n.º 4
0
def check_for_followed_by_args(cmd, command_args, project_template):
    if not cmd.followed_by_template and not cmd.followed_by_command:
        return command_args # nothing to check

    command = None

    if cmd.followed_by_template and cmd.followed_by_command:
        # If no arguments, there is something obviously wrong
        if len(command_args) == 0:
            if project_template:
                templatetools.usage_error(_("No command provided to %s command.") % cmd.name, cmd=cmd, template=project_template)
            else:
                templatetools.usage_error(_("No template or command provided to %s command.") % cmd.name, cmd=cmd)
        # At least one argument.  What is it?  First check if it's a command if we already have a template
        if project_template:
            command = commands.get_command(command_args[0], project_template)
            if command:
                command_args.insert(0, project_template) # use default template
            elif not command and not check_template_exists(command_args[0]):
                # Wasn't a command or a template name, but we are in the context of a template
                templatetools.usage_error(_("No %s command found in %s template.") % (command_args[0], project_template), cmd=cmd, template=project_template)
        if not command:
            # must be a template name then (or nonsense)
            if not check_template_exists(command_args[0]):
                command = commands.get_command(command_args[0]) # did user provid a valid builtin command?
                if command:
                    command_args.insert(0, 'builtins')
                elif len(command_args) == 1:
                    templatetools.usage_error(_("%s is neither a template nor a standard command.") % (command_args[0]), cmd=cmd)
                else:
                    templatetools.usage_error(_("Template %s does not exist.") % (command_args[0]), cmd=cmd, show_templates_for=None)
            project_template = command_args[0]
            # OK, we have a template!
            if len(command_args) < 2:
                templatetools.usage_error(_("No command provided to %s command.") % cmd.name, cmd=cmd, template=project_template)
            command = commands.get_command(command_args[1], project_template)
            if not command:
                templatetools.usage_error(_("No %s command found in %s template.") % (command_args[1], project_template), cmd=cmd, template=project_template)

    elif cmd.followed_by_template:
        if len(command_args) > 0:
            if check_template_exists(command_args[0]):
                project_template = command_args[0]
        if not project_template:
            templatetools.usage_error(_("No template provided to %s command.") % cmd.name, cmd=cmd)

    elif cmd.followed_by_command:
        if len(command_args) > 0:
            command = commands.get_command(command_args[0], project_template)
            if not command:
                templatetools.usage_error(_("No %s command found.") % command_args[0], cmd=cmd, template=project_template)
        if not command:
            templatetools.usage_error(_("No command provided to %s command.") % cmd.name, cmd=cmd, template=project_template)

    return command_args
Exemplo n.º 5
0
    def onMessage(self, msg):
        if msg["type"] == 'chat' and hasattr(msg, "body"):
            cmd_list = str(msg.body).split(" ")
            cmd = cmd_list[0]
            args = cmd_list[1:]
            kwargs = {}
            if "=" in cmd:
                args = []
                kwargs = utils.str_to_dict(" ".join(cmd_list[1:]))

            commands.get_command(cmd)(self, msg, *args, **kwargs)
Exemplo n.º 6
0
  def run(self, cmd):
    from inspect import getdoc

    if not cmd:
      for cmd in get_commands():
        print(getdoc(get_command(cmd)).split('\n')[0])
      return

    if not get_command(cmd):
      print('No such command. Try "help" for a list of all commands.')
    else:
      print(getdoc(get_command(cmd)))
Exemplo n.º 7
0
    def run(self, cmd):
        from inspect import getdoc

        if not cmd:
            for cmd in get_commands():
                print(getdoc(get_command(cmd)).split('\n')[0])
            return

        if not get_command(cmd):
            print('No such command. Try "help" for a list of all commands.')
        else:
            print(getdoc(get_command(cmd)))
Exemplo n.º 8
0
	def __handle_new_connection(self):
		"""This is called whenever a new connection is initiated"""
		sock, address = self.server_client.socket.accept()
		client = clients.Client(ip=address[0], name=address[0], protocol=self.encoders, socket=sock, server=self)
		self.clients.append(client)
		cmd = commands.get_command("Broadcast", self, self.server_client, ["{0} has joined the chat!".format(client.name), [client.name]])
		cmd.execute()
def quickly(project_template, project_dir, command_args, shell_completion=False):
    """Create a new quickly template from an existing one"""

    # We have nothing for this
    if shell_completion:
        return("")

    project_template = command_args[0]
    if len(command_args) < 2:
        cmd = commands_module.get_command('quickly', project_template)
        templatetools.usage_error(_("No destination template name provided."), cmd=cmd, template=project_template)

    destination_path = os.path.expanduser("~/quickly-templates/")
    # create ~/quickly-templates/ if needed
    if not os.path.exists(destination_path):
        os.makedirs(destination_path)

    template_destination_path = destination_path + command_args[1]
    if os.path.exists(template_destination_path):
        print _("%s already exists." % template_destination_path)
        return 1

    if not os.path.exists(template_destination_path):
        print _("Copy %s to create new %s template") % (project_template, template_destination_path)

    try:
        template_source_path = tools.get_template_directory(project_template)
    except tools.template_path_not_found, e:
        print(e)
        return 1
Exemplo n.º 10
0
 def stop(self):
     """Warns the connected client that the server is going down then close all connection"""
     logging.info("Server stopped")
     cmd = commands.get_command("Broadcast", self, self.server_client,
                                ["I AM GOING DOWN."])
     cmd.execute()
     self.kill()
Exemplo n.º 11
0
def parse_commands(machine):
    global ERROR_FREE_CODE

    while not machine.instruction_queue.empty():
        command = machine.instruction_queue.get()

        command_directive, params = get_command_directive(command)

        command_directive = command_directive.strip()

        command_return_message = commands.get_command()[command_directive](
            params, machine)

        if command_return_message.startswith("Error"):
            print(command_return_message)
            ERROR_FREE_CODE = False
            break

        if command_return_message == '==> Emergency stop':
            machine.message_queue.put(command_return_message)
            break

        if command_return_message == '==> Unconditional stop':
            machine.message_queue.put(command_return_message)
            break

        machine.message_queue.put(command_return_message)
Exemplo n.º 12
0
def main(argv):
    loglevel = logging.ERROR
    load_commands()

    # handle input switches and parameters using `getopt.getopt` function
    # there should be handled following switches:
    # -h and --help   - display help message prepared in _usage function above
    # -v and --verbose  - display additional debug ouput, set log level as logging.DEBUG
    #
    # There should be accepted only one input parameter, namely <command name>
    #
    # Missing input parameters should cause displaying help message.
    # Wrong command name in the first parameter, should cause displaying error message.

    # !!!Your code here!!!

    logger = _configlog(loglevel)
    logger.debug('START')
    try:
        cmdclass = commands.get_command(command)
        # execute command provided by user as first parameter
        # `cmdclass` it should be class, which implements given command
        # this class should be instantiated with appropriate arguments
        # and `execute` method of this instance should be called
        #
        # !!!Your code here!!!
        
    except Exception, ex:
        logger.error('Command error: %s' % ex)
Exemplo n.º 13
0
def main(argv):
    loglevel = logging.ERROR
    load_commands()

    # handle input switches and parameters using `getopt.getopt` function
    # there should be handled following switches:
    # -h and --help   - display help message prepared in _usage function above
    # -v and --verbose  - display additional debug ouput, set log level as logging.DEBUG
    #
    # There should be accepted only one input parameter, namely <command name>
    #
    # Missing input parameters should cause displaying help message.
    # Wrong command name in the first parameter, should cause displaying error message.

    # !!!Your code here!!!

    logger = _configlog(loglevel)
    logger.debug('START')
    try:
        cmdclass = commands.get_command(command)
        # execute command provided by user as first parameter
        # `cmdclass` it should be class, which implements given command
        # this class should be instantiated with appropriate arguments
        # and `execute` method of this instance should be called
        #
        # !!!Your code here!!!

    except Exception, ex:
        logger.error('Command error: %s' % ex)
Exemplo n.º 14
0
	def disconnect_client(self, client):
		"""
		Disconnect a client and announce it to the world.
		"""
		self.clients.remove(client)
		client.socket.close()
		cmd = commands.get_command("Broadcast", self, self.server_client, ["{0} has left the chat!".format(client.name), [client.name]])
		cmd.execute()
Exemplo n.º 15
0
def main():

	if len(argv) == 1:
		with open('description.txt') as f:
			print f.read()
	else:
		command = argv[1]
		command = get_command(argv[1:])
		command.execute()
Exemplo n.º 16
0
    def disconnect_client(self, client):
        """
		Disconnect a client and announce it to the world.
		"""
        self.clients.remove(client)
        client.socket.close()
        cmd = commands.get_command(
            "Broadcast", self, self.server_client,
            ["{0} has left the chat!".format(client.name), [client.name]])
        cmd.execute()
Exemplo n.º 17
0
def main(cmd_name, *args):
    cmd = commands.get_command(cmd_name)
    if cmd is None:
        logger.error('Unknown command %s', cmd)
        return 1

    zk = get_client('localhost')
    result = cmd(zk, *args)
    if result is not None:
        print(result)
Exemplo n.º 18
0
 def loop(self):
     ok = True
     while ok is True:
         epidb = self._context.epidb
         line = raw_input(str(epidb.echo(self._context.user_key)) + " > ")
         cmd = line.strip()
         if len(cmd) == 0:
             continue
         command = get_command(cmd)
         if command is None:
             continue
         command(self._context)
Exemplo n.º 19
0
 def __handle_new_connection(self):
     """This is called whenever a new connection is initiated"""
     sock, address = self.server_client.socket.accept()
     client = clients.Client(ip=address[0],
                             name=address[0],
                             protocol=self.encoders,
                             socket=sock,
                             server=self)
     self.clients.append(client)
     cmd = commands.get_command(
         "Broadcast", self, self.server_client,
         ["{0} has joined the chat!".format(client.name), [client.name]])
     cmd.execute()
Exemplo n.º 20
0
 def __handle_request(self, caller):
     """This is called whenever data is received from one of the client."""
     try:
         data = caller.receive()
         logging.debug("Parsing this data: '" + data + "'")
         result = self.parser.parse(data)
         logging.debug("Result of parsing: '" + result.command_name + "(" +
                       ",".join(result.command_arguments) + ")'")
         cmd = commands.get_command(result.command_name, self, caller,
                                    result.command_arguments)
         cmd.execute()
     except commands.ArgumentsValidationError as e:
         #Command arguments did not validate.
         print(e)
         print("asdasdasdasd")
         cmd = commands.get_command("Whisper", self, self.server_client,
                                    [caller.name, str(e)])
         cmd.execute()
     except commands.ExecutionFailedError as e:
         #Tell the client that the command could not be executed properly.
         cmd = commands.get_command(
             "Whisper", self, self.server_client,
             [caller.name, "Command execution failed"])
         cmd.execute()
         logging.exception(e)
     except clients.SocketError as e:
         #Client probably just disconnected.
         logging.debug("SocketError while handling request.")
         logging.exception(e)
         self.disconnect_client(caller)
     except clients.ClientIsNotFinishedSendingError as e:
         #Client has not finished sending it's data.
         pass
     except NameError as e:
         # The command is not recognized.
         cmd = commands.get_command("Whisper", self, self.server_client,
                                    [caller.name, "Unrecognized command"])
         cmd.execute()
Exemplo n.º 21
0
def main(argv):
    loglevel = logging.ERROR
    load_commands()
    comm_name = "comm"
    # handle input switches and parameters using `getopt.getopt` function
    # there should be handled following switches:
    # -h and --help   - display help message prepared in _usage function above
    # -v and --verbose  - display additional debug ouput, set log level as logging.DEBUG
    #
    # There should be accepted only one input parameter, namely <command name>
    #
    # Missing input parameters should cause displaying help message.
    # Wrong command name in the first parameter, should cause displaying error message.
    #print len(sys.argv[1:])
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'ho:v')
    except getopt.GetoptError as err:
        _usage(1)
        sys.exit()
    if len(sys.argv[1:]) == 0 or len(args) == 0:
            _usage(1)
            sys.exit()
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            _usage(1)
            sys.exit()
        elif opt in ('-v', '--verbose'):
            comm_name = args[0]
        else:
            _usage(1)
            sys.exit()
    # !!!Your code here!!!

    logger = _configlog(loglevel)
    logger.debug('START')
    try:
        cmdclass = commands.get_command(comm_name)
        # execute command provided by user as first parameter
        # `cmdclass` it should be class, which implements given command
        # this class should be instantiated with appropriate arguments
        # and `execute` method of this instance should be called
        # !!!Your code here!!!
        some = cmdclass()
        #logger.info('Command: %s' % some.cmd_description)
        some.execute()

    except ValueError as ex:
        logger.error('Command error: %s' % ex)

    logger.debug('%r' % 'DONE')
Exemplo n.º 22
0
def pipe_commands(args, channel):
    pipelist = args["args"].copy()
    pipelist.insert(0,args["command"])
    l = isplit(pipelist,"|")
    out = None
    for i in l:
        cmd = i[0].strip(".")
        a = i[1:]
        if out:
            a.append(out)
        args["command"] = cmd
        args["args"] = a
        print(a)
        c = get_command(args["command"])
        print(type(c), c)
        out = "".join(c(args))
    sendmsg(channel, out)
def help(project_template, project_dir, command_args, shell_completion=False):
    """Get help from commands"""

    # We have nothing for this
    if shell_completion:
        return("")

    # main quickly script has already made sure input is sane

    project_template = command_args[0]
    command_name = command_args[1]
    command = commands_module.get_command(command_name, project_template)

    # Also print usage if we can
    if command.usage():
        print # blank line before getting to help
    return command.help(project_dir, command_args)
Exemplo n.º 24
0
def pipe_commands(args, channel):
    pipelist = args["args"].copy()
    pipelist.insert(0,args["command"])
    l = isplit(pipelist,"|")
    out = None
    for i in l:
        cmd = i[0].strip(".")
        a = i[1:]
        if out:
            a.append(out)
        args["command"] = cmd
        args["args"] = a
        print(a)
        c = get_command(args["command"])
        print(type(c), c)
        if not cmd == "rate" or not cmd == "r8":
            out = "".join(c(args))
    sendmsg(channel, out)
Exemplo n.º 25
0
Arquivo: main.py Projeto: czinn/ebb
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('db', help='db connection string')
    args = parser.parse_args()

    connect(args.db)

    history = InMemoryHistory()
    while(True):
        command_name = ui.prompt_options('>', command_list(), strict=True, history=history)
        try:
            command = get_command(command_name)
        except:
            ui.print('Invalid command')
            continue
        session = Session()
        try:
            command(session)
        except KeyboardInterrupt:
            session.rollback()
            ui.print('Command cancelled')
def pre_create(command_template, project_template, project_dir, command_args):
    """Create the project directory before create command call"""

    if len(command_args) < 1:
        cmd = commands_module.get_command('create', project_template)
        templatetools.usage_error(_("No project name specified."), cmd=cmd, template=project_template)
 
    path_and_project = command_args[0].split('/')
    project_name = path_and_project[-1]
    
    # if a path is not present, create it
    if len(path_and_project) > 1:
        path = str(os.path.sep).join(path_and_project[0:-1])
        if not os.path.exists(path):
            os.makedirs(path)
        os.chdir(path)
    
    # check that project name follow quickly rules and reformat it.
    try:
        project_name = templatetools.quickly_name(project_name)
    except templatetools.bad_project_name, e:
        print(e)
        return(4)
Exemplo n.º 27
0
def check_for_followed_by_args(cmd, command_args):
    if not cmd.followed_by_command:
        return command_args # nothing to check

    command = None

    if cmd.followed_by_command:
        # If no arguments, there is something obviously wrong
        if len(command_args) == 0:
            usage_error(_("No command provided to %s command.") % cmd.name, cmd=cmd)

        command = commands.get_command(command_args[0]) # did user provid a valid builtin command?
        if command:
            command_args.insert(0, 'builtins')
        elif len(command_args) == 1:
            usage_error(_("%s is not a standard command.") % (command_args[0]), cmd=cmd)

        if len(command_args) > 1:
            if not command:
                usage_error(_("No %s command found.") % command_args[0], cmd=cmd)
        if not command:
            usage_error(_("No command provided to %s command.") % cmd.name, cmd=cmd)

    return command_args
Exemplo n.º 28
0
def check_for_followed_by_args(cmd, command_args, project_template):
    if not cmd.followed_by_template and not cmd.followed_by_command:
        return command_args  # nothing to check

    command = None

    if cmd.followed_by_template and cmd.followed_by_command:
        # If no arguments, there is something obviously wrong
        if len(command_args) == 0:
            if project_template:
                templatetools.usage_error(
                    _("No command provided to %s command.") % cmd.name,
                    cmd=cmd,
                    template=project_template)
            else:
                templatetools.usage_error(
                    _("No template or command provided to %s command.") %
                    cmd.name,
                    cmd=cmd)
        # At least one argument.  What is it?  First check if it's a command if we already have a template
        if project_template:
            command = commands.get_command(command_args[0], project_template)
            if command:
                command_args.insert(0,
                                    project_template)  # use default template
            elif not command and not check_template_exists(command_args[0]):
                # Wasn't a command or a template name, but we are in the context of a template
                templatetools.usage_error(
                    _("No %s command found in %s template.") %
                    (command_args[0], project_template),
                    cmd=cmd,
                    template=project_template)
        if not command:
            # must be a template name then (or nonsense)
            if not check_template_exists(command_args[0]):
                command = commands.get_command(
                    command_args[0]
                )  # did user provid a valid builtin command?
                if command:
                    command_args.insert(0, 'builtins')
                elif len(command_args) == 1:
                    templatetools.usage_error(
                        _("%s is neither a template nor a standard command.") %
                        (command_args[0]),
                        cmd=cmd)
                else:
                    templatetools.usage_error(
                        _("Template %s does not exist.") % (command_args[0]),
                        cmd=cmd,
                        show_templates_for=None)
            project_template = command_args[0]
            # OK, we have a template!
            if len(command_args) < 2:
                templatetools.usage_error(
                    _("No command provided to %s command.") % cmd.name,
                    cmd=cmd,
                    template=project_template)
            command = commands.get_command(command_args[1], project_template)
            if not command:
                templatetools.usage_error(
                    _("No %s command found in %s template.") %
                    (command_args[1], project_template),
                    cmd=cmd,
                    template=project_template)

    elif cmd.followed_by_template:
        if len(command_args) > 0:
            if check_template_exists(command_args[0]):
                project_template = command_args[0]
        if not project_template:
            templatetools.usage_error(
                _("No template provided to %s command.") % cmd.name, cmd=cmd)

    elif cmd.followed_by_command:
        if len(command_args) > 0:
            command = commands.get_command(command_args[0], project_template)
            if not command:
                templatetools.usage_error(_("No %s command found.") %
                                          command_args[0],
                                          cmd=cmd,
                                          template=project_template)
        if not command:
            templatetools.usage_error(_("No command provided to %s command.") %
                                      cmd.name,
                                      cmd=cmd,
                                      template=project_template)

    return command_args
Exemplo n.º 29
0
 def whisp_client(self, message, client):
     cmd = commands.get_command("Whisper", self, self.server_client,
                                [client.name, message])
     cmd.execute()
Exemplo n.º 30
0
        valid_data = process_data(data)
    except Exception as e:
        continue
    if not valid_data:
        continue
    print(data)
    for ircmsg in process_data(data):
        if "PING :" in ircmsg:
            ircsock.send(bytes("PONG :ping\n", 'UTF-8'))
        elif "/QUOTE PONG" in ircmsg:
            confirm = "PONG " + ircmsg.split()[-1:][0] + "\r\n"
            ircsock.send(bytes(confirm, 'UTF-8'))
            for channel in channel_list:
                joinchan(channel)
                time.sleep(.5)
        elif any(channel in ircmsg for channel in channel_list):
            try:
                args = parsemsg(str(ircmsg))
                channel = args['channel']
                if "|" in args["args"]:
                    pipe_commands(args, channel)
                else:
                    cmd = get_command(args["command"])
                    try:
                        sendmsg(channel, cmd(args))
                    except Exception as e:
                        print(e)
                        sendmsg(channel, (str(e)))
            except Exception as e:
                pass
Exemplo n.º 31
0
	def stop(self):
		"""Warns the connected client that the server is going down then close all connection"""
		logging.info("Server stopped")
		cmd = commands.get_command("Broadcast", self, self.server_client, ["I AM GOING DOWN."])
		cmd.execute()
		self.kill()
Exemplo n.º 32
0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
time.sleep(.5)
s.connect((server, port))
time.sleep(.5)
ircsock = ssl.wrap_socket(s)
time.sleep(.5)
ircsock.send(bytes("USER %s %s %s :some stuff\n" % (botnick, botnick, botnick), 'UTF-8'))
time.sleep(.5)
ircsock.send(bytes("NICK %s\n" % botnick, 'UTF-8'))
time.sleep(.5)
joinchan(channel)

while True:
    data = ircsock.recv(1024)
    for ircmsg in process_data(data):
        if "PING :" in ircmsg:
            ircsock.send(bytes("PONG :ping\n", 'UTF-8'))
        elif channel in ircmsg:
            args = parsemsg(str(ircmsg))
            if "|" in args["args"]:
                pipe_commands(args, channel)
            else:
                cmd = get_command(args["command"])
                try:
                    sendmsg(channel, cmd(args))
                except Exception as e:
                    print(e)
                    sendmsg(channel, (str(e)))
        else:
            continue
Exemplo n.º 33
0
	def whisp_client(self, message, client):
		cmd = commands.get_command("Whisper",self, self.server_client, [client.name, message])
		cmd.execute()
Exemplo n.º 34
0
CMD_DICT_ARGS = {'group': group_bookmarks, 'add': add_bookmarks, 'delete':del_bookmarks}
CMD_DICT = {'open':open_bookmarks, 'list': list_bookmarks}

def run_command(cmd, cmd_string):
    """Run the command entered by the user.
    Args:
        cmd (str): This is the command, e.g. group
        cmd_string (str): The parameters of the command

    Returns:
        None

    """
    cmd = cmd.lower()
    if cmd in CMD_DICT_ARGS:
        func = CMD_DICT_ARGS[cmd]
        func(cmd_string)
    elif cmd in CMD_DICT:
        func = CMD_DICT[cmd]
        func()
    else:
        print_usage()

if __name__ == '__main__':
    if not sys.argv[1:]:
        print_usage()
        exit()
    else:
        (cmd, cmd_string) = get_command(sys.argv)
        run_command(cmd, cmd_string)