Exemplo n.º 1
0
    def cmdloop(self, line):
        """It starts interactive mode with command to be executed.

        Args:
            line (str): command with args to be executed.
        """
        Cmd.onecmd(self, line)
        Cmd.cmdloop(self)
Exemplo n.º 2
0
    def onecmd(self, line):
        if line == 'EOF' or line.lower() == "quit":
            self.conn.close()
            return True

        if line == 'h':
            line = 'help'

        Cmd.onecmd(self, line)
Exemplo n.º 3
0
    def onecmd(self, line):
        if line == 'EOF' or line.lower() == "quit":
            self.conn.close()
            return True

        if line == 'h':
            line = 'help'

        Cmd.onecmd(self, line)
Exemplo n.º 4
0
 def onecmd(self, line):
     lines = line.split("&&")
     try:
         for line in lines:
             line = self.doAlias(line)
             Cmd.onecmd(self, line)
     except SystemExit:
         raise
     except Exception, msg:
         #self.vprint(traceback.format_exc())
         self.vprint("\nERROR: (%s) %s" % (msg.__class__.__name__, msg))
Exemplo n.º 5
0
 def onecmd(self, line):
     lines = line.split("&&")
     try:
         for line in lines:
             line = self.doAlias(line)
             Cmd.onecmd(self, line)
     except SystemExit:
         raise
     except Exception, msg:
         self.vprint(traceback.format_exc())
         self.vprint("\nERROR: (%s) %s" % (msg.__class__.__name__, msg))
Exemplo n.º 6
0
 def onecmd(self, line):
     self.dprint('line:"{0}"'.format(line))
     cmd, arg, line = self.parseline(line)
     func = getattr(self, "hidden_{0}".format(cmd), None)
     try:
         if func:
             self.dprint(
                 'Running onecmd func: {0}.hidden_{1}("{2}")'.format(
                     self, cmd, arg))
             return func(arg)
         else:
             self.dprint(
                 'Did not find func, running Cmd.onecmd(line="{0}")'.format(
                     line))
             return Cmd.onecmd(self, line)
     except CliError as AE:
         self.eprint("ERROR: " + str(AE))
         return self.onecmd("? " + str(line))
     except SystemExit:
         raise
     except Exception as FE:
         if self.env.simplecli_config.debug:
             print_exc(file=self.stderr)
         self.eprint('\n"{0}": {1}({2})'.format(line, FE.__class__.__name__,
                                                str(FE)))
         self.oprint('\n')
Exemplo n.º 7
0
	def onecmd(self, s):
		try:	
			return Cmd.onecmd(self, s)
		except KeyboardInterrupt:
			#@TODO: this is a work-around, find out what's going on
			os.system("stty echo")
			print '\n'
Exemplo n.º 8
0
 def onecmd(self, s):
     try:
         return Cmd.onecmd(self, s)
     except KeyboardInterrupt:
         #@TODO: this is a work-around, find out what's going on
         os.system("stty echo")
         print '\n'
Exemplo n.º 9
0
 def onecmd(self, line):
     log.debug('onecmd("{}")'.format(line))
     try:
         return Cmd.onecmd(self, line)
     except BadCliArguments:
         self.echo(_('Bad arguments'))
         return False
Exemplo n.º 10
0
 def onecmd(self, line):
     ### Wraps commands and catches exceptions
     try:
         return Cmd.onecmd(self, line)
     except SmarttClientException as e:
         print REDCOLORCODE + str(e) + ENDOFCOLORCODE
         return False
Exemplo n.º 11
0
 def onecmd(self, line):
     self.session = Session()
     ret = None
     try:
         ret = Cmd.onecmd(self, line)
         self.session.commit()
     except Exception, e:
         print e
Exemplo n.º 12
0
 def onecmd(self, line):
     is_script, script = get_script_cmd(line,
                                        self._location.get_real_path())
     if is_script:
         self.do_shell(line)
     else:
         self.last_cmd_output = Cmd.onecmd(self, line)
         return self.last_cmd_output
Exemplo n.º 13
0
 def onecmd(self, line):
     try:
         ret = Cmd.onecmd(self, line)
         self.session.commit()
         return ret
     except Exception, e:
         print e
         return None
Exemplo n.º 14
0
    def testHelp(self):
        cmd = YokadiCmd()
        for attr in dir(cmd):
            if not attr.startswith("do_"):
                continue

            yokadiCommand = attr[3:]
            try:
                # Execute the command, but redirect stdout and stderr to
                # /dev/null to avoid flooding the terminal
                with to_devnull(sys.stdout), to_devnull(sys.stderr):
                    # We use Cmd implementation of onecmd() because YokadiCmd
                    # overrides it to catch exceptions
                    Cmd.onecmd(cmd, "help " + yokadiCommand)
            except Exception as exc:
                print("'help %s' failed" % yokadiCommand)
                raise
Exemplo n.º 15
0
    def testHelp(self):
        cmd = YokadiCmd()
        for attr in dir(cmd):
            if not attr.startswith("do_"):
                continue

            yokadiCommand = attr[3:]
            try:
                # Execute the command, but redirect stdout and stderr to
                # /dev/null to avoid flooding the terminal
                with to_devnull(sys.stdout), to_devnull(sys.stderr):
                    # We use Cmd implementation of onecmd() because YokadiCmd
                    # overrides it to catch exceptions
                    Cmd.onecmd(cmd, "help " + yokadiCommand)
            except Exception:
                print("'help %s' failed" % yokadiCommand)
                raise
Exemplo n.º 16
0
def process_command(processor_cmd: cmd.Cmd, command: str) -> bool:
    is_stopping: bool
    if command:
        command = processor_cmd.precmd(command)
        is_stopping = processor_cmd.onecmd(command)
        is_stopping = processor_cmd.postcmd(is_stopping, command)
    else:
        is_stopping = True
    return is_stopping
Exemplo n.º 17
0
    def onecmd(self, line):
        if line.startswith('!'):
            return Cmd.onecmd(self, line[1:])

        parsed = parser(line).form()
        try:
            print self.evaluator([parsed]).eval()
        except Exception as e:
            print repr(e)
Exemplo n.º 18
0
    def onecmd(self, line):

        # check for empty line and emptymeth
        if not line.strip() and self.emptymeth:
            self.emptymeth()
            return

        self.emptymeth = None
        lines = line.split("&&")
        try:
            for line in lines:
                line = self.aliascmd( line )
                Cmd.onecmd(self, line)
        except SystemExit:
            raise
        except Exception, msg:
            if self.config.cli.verbose:
                self.vprint(traceback.format_exc())
            self.vprint("\nERROR: (%s) %s" % (msg.__class__.__name__,msg))
Exemplo n.º 19
0
 def onecmd(self, line):
     try:
         return _Cmd.onecmd(self, line)
     except ConcurAPIError as error:
         print "%s: %s" % (type(error).__name__, error[0])
         print error[1]
     except Exception as error:
         print "%s: %s" % (type(error).__name__, error)
         import traceback
         traceback.print_exc()
Exemplo n.º 20
0
Arquivo: sh.py Projeto: machste/pyrail
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except KeyboardInterrupt:
         cmd, arg, line = self.parseline(line)
         try:
             abort_func = getattr(self, "abort_" + cmd)
         except AttributeError:
             return False
         return abort_func()
Exemplo n.º 21
0
Arquivo: cli.py Projeto: wflk/vivisect
    def onecmd(self, line):

        # check for empty line and emptymeth
        if not line.strip() and self.emptymeth:
            self.emptymeth()
            return

        self.emptymeth = None
        lines = line.split("&&")
        try:
            for line in lines:
                line = self.aliascmd(line)
                Cmd.onecmd(self, line)
        except SystemExit:
            raise
        except Exception, msg:
            if self.config.cli.verbose:
                self.vprint(traceback.format_exc())
            self.vprint("\nERROR: (%s) %s" % (msg.__class__.__name__, msg))
Exemplo n.º 22
0
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line=line.decode(tui.ENCODING)
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except YokadiException, e:
         tui.error("*** Yokadi error ***\n\t%s" % e)
Exemplo n.º 23
0
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line = line.decode(tui.ENCODING)
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except UnicodeDecodeError, e:
         tui.error("Unicode decoding error. Please check you locale and terminal settings (%s)." % e)
Exemplo n.º 24
0
    def onecmd(self, line):
        cmd, args, line = self.parseline(line) 
        args = shlex.split(args)
        if cmd in self.command.list:
            nargs = int(self.command.list[cmd]['args'])

            if nargs != len(args):
                print('wrong number of arguments (expected %i)' % nargs)
            else:
                self.command.list[cmd]['exec'](self.command, *args)
        else:
            return Cmd.onecmd(self, line)
Exemplo n.º 25
0
 def onecmd(self, line):
     try:
         cmd, arg, line = self.parseline(line)
         if arg in ("-h", "--help"):
             try:
                 getattr(self, "help_"+cmd)()
                 return None
             except AttributeError:
                 pass
         return Cmd.onecmd(self, line)
     except Error, e:
         iface.error(unicode(e))
         return None
Exemplo n.º 26
0
 def onecmd(self, s):
     """ This method overides the Cmd.onecmd method, but eventully
         calls the Cmd.onecmd function. The purpose of this function
         is to catch the errors at a single point, rather than all
         over the code.
     """
     try:
         return Cmd.onecmd(self, s)
     except Exception as e:
         utils.error(e)
         command = s.split()[0]
         self.do_help(command)
         return False
Exemplo n.º 27
0
 def onecmd(self, s):
     """ This method overides the Cmd.onecmd method, but eventully
         calls the Cmd.onecmd function. The purpose of this function
         is to catch the errors at a single point, rather than all
         over the code.
     """
     try:
         return Cmd.onecmd(self, s)
     except Exception as e:
         utils.error(e)
         command = s.split()[0]
         self.do_help(command)
         return False
Exemplo n.º 28
0
    def onecmd(self, s):
        self.previous_sentence = self.current_sentence

        while True:
            potential_next = self.sentences[randint(0, len(sentences))]
            if potential_next["SentenceId"] not in self.trained:
                self.current_sentence = potential_next
                break
            else:
                print "%s Seen already" % (potential_next["SentenceId"])

        self.prompt = self.current_sentence['Sentence'] + " : "
        return Cmd.onecmd(self, s)
Exemplo n.º 29
0
 def onecmd(self, line):
     try:
         cmd, arg, line = self.parseline(line)
         if arg in ("-h", "--help"):
             try:
                 getattr(self, "help_" + cmd)()
                 return None
             except AttributeError:
                 pass
         return Cmd.onecmd(self, line)
     except Error, e:
         iface.error(unicode(e))
         return None
Exemplo n.º 30
0
Arquivo: main.py Projeto: bport/yokadi
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line = line.decode(tui.ENCODING)
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except UnicodeDecodeError, e:
         tui.error(
             "Unicode decoding error. Please check you locale and terminal settings (%s)."
             % e)
Exemplo n.º 31
0
    def onecmd(self, s):

        cmd_result = Cmd.onecmd(self, s)

        # Send request to server
        self.protocol.send_message(s)
        _server_result = self.protocol._response_chunk

        if _server_result is not None:
            print(_server_result)
        _server_result = None

        return cmd_result
Exemplo n.º 32
0
    def onecmd(self, s):
        self.previous_sentence = self.current_sentence

        while True:
            potential_next = self.sentences[randint(0, len(sentences))]
            if potential_next["SentenceId"] not in self.trained:
                self.current_sentence = potential_next
                break
            else:
                print "%s Seen already" % (potential_next["SentenceId"])

        self.prompt = self.current_sentence['Sentence'] + " : "
        return Cmd.onecmd(self, s)
Exemplo n.º 33
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except SystemExit:
         raise
     except:
         from waterworks.Tools import get_current_traceback_tuple
         exc_class, exc, desc = get_current_traceback_tuple()
         print ansi.RED + ''.join(desc).strip() + ansi.BOLD
         if exc is None:
             print exc_class
         else:
             print "%s: %s" % (exc_class.__name__, exc)
         sys.stdout.write(ansi.RESET)
Exemplo n.º 34
0
    def onecmd(self, line):
        """Wrapper for Cmd.onecmd() that handles errors.
		Also handles line being a list, to ease execution of a single command from the command line of this app.
		"""
        if isinstance(line, list): line = self.lineFromArgs(line)
        try:
            line = self.precmd(line)
            result = Cmd.onecmd(self, line)
            return result
        except KeyboardInterrupt:
            self.msg("Keyboard interrupt")
        except Exception as e:
            self.msg(err())
            return
Exemplo n.º 35
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except SystemExit:
         raise
     except:
         from waterworks.Tools import get_current_traceback_tuple
         exc_class, exc, desc = get_current_traceback_tuple()
         print ansi.RED + ''.join(desc).strip() + ansi.BOLD
         if exc is None:
             print exc_class
         else:
             print "%s: %s" % (exc_class.__name__, exc)
         sys.stdout.write(ansi.RESET)
Exemplo n.º 36
0
 def onecmd(self, line):
     try:
         if not self.blocked or line == 'EOF' or line.startswith('stage'):
             return Cmd.onecmd(self, line)
         else:
             return False
     except subprocess.CalledProcessError as e:
         log.info(on_color('RED', 'Command error: ' + str(e)))
         if self.args.exit_on_err or not self.is_interactive():
             self.abort()
     except KeyboardInterrupt as e:
         log.info(on_color('RED', '[interrupted]'))
         if self.args.exit_on_err or not self.is_interactive():
             self.last_exc = sys.exc_info()
             self.abort()
Exemplo n.º 37
0
    def onecmd(self, line):
        '''Modified Cmd.cmd.onecmd so that it can detect if a file is a script,
        and can run it appropriately

        Keyword arguments:
        line - string.  Is what the user enters at the terminal

        Check if value entered is a shell script
        '''

        is_script, script = get_script_cmd(line, self.real_path)
        if is_script:
            # TODO: what is this?
            self.do_shell(line)
        else:
            self.last_cmd_output = Cmd.onecmd(self, line)
            return self.last_cmd_output
Exemplo n.º 38
0
    def onecmd(self, line):
        if line is None:
            return
        orig_line = line
        cmd, args, line = self.parseline(line)
        if cmd == 'exit' and not orig_line.strip() == 'exit':
            print('type "exit" to quit the console')
            return

        if os.getenv('OBJEX_DEBUG', '') and cmd not in self.completenames(''):
            command, arg, line = Cmd.parseline(self, line)
            if command is None:  # empty line comes through as None not ''
                reader_func = None
            else:
                reader_func = getattr(self.reader, command, None)
            if reader_func:
                args = []
                mark = 0
                chunks = arg.split()
                for i in range(len(chunks) + 1):
                    attempt = " ".join(chunks[mark:i]).strip()
                    try:  # ast.literal_eval takes 4 microseconds; no perf issue
                        args.append(ast.literal_eval(attempt))
                        mark = i
                    except SyntaxError:
                        pass
                if mark < len(chunks):
                    print("ERROR unparsed input: ", " ".join(chunks[mark:]))
                else:
                    try:
                        res = reader_func(*args)
                        pprint.pprint(res)
                    except Exception:
                        import traceback; traceback.print_exc()
                        print("args:", args)
                print()
                return

        if line and line != 'EOF' and cmd and self.completenames(cmd):
            self.cmd_history.append({'line': line, 'cmd': cmd, 'args': args, 'options': []})
        try:
            return Cmd.onecmd(self, line)
        except Exception:
            # TODO: better exception handling can go here, maybe pdb with OBJEX_DEBUG=True
            self.cmd_history.pop()
            raise
Exemplo n.º 39
0
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line = line
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except UnicodeDecodeError as e:
         tui.error(
             "Unicode decoding error. Please check you locale and terminal settings (%s)."
             % e)
     except UnicodeEncodeError as e:
         tui.error(
             "Unicode encoding error. Please check you locale and terminal settings (%s)."
             % e)
     except BadUsageException as e:
         tui.error("*** Bad usage ***\n\t%s" % e)
         cmd = line.split(' ')[0]
         self.do_help(cmd)
     except YokadiException as e:
         tui.error("*** Yokadi error ***\n\t%s" % e)
     except IOError as e:
         # We can get I/O errors when yokadi is piped onto another shell commands
         # that breaks.
         print("*** I/O error ***\n\t%s" % e, file=sys.stderr)
     except KeyboardInterrupt:
         print("*** Break ***")
     except Exception as e:
         tui.error("Unhandled exception (oups)\n\t%s" % e)
         print("This is a bug of Yokadi, sorry.")
         print(
             "Send the above message by email to Yokadi developers ([email protected]) to help them make"
             " Yokadi better.")
         cut = "---------------------8<----------------------------------------------"
         print(cut)
         traceback.print_exc()
         print("--")
         print("Python: %s" % sys.version.replace("\n", " "))
         print("SQL Alchemy: %s" % sqlalchemy.__version__)
         print("OS: %s (%s)" % os.uname()[0:3:2])
         print("Yokadi: %s" % yokadi.__version__)
         print(cut)
         print()
Exemplo n.º 40
0
    def onecmd(self, line):
        '''Modified Cmd.cmd.onecmd so that it can detect if a file is a script,
        and can run it appropriately

        Keyword arguments:
        line - string.  Is what the user enters at the terminal

        Check if value entered is a shell script
        '''

        is_script, script = get_script_cmd(
            line,
            self.real_path
        )
        if is_script:
            # TODO: what is this?
            self.do_shell(line)
        else:
            self.last_cmd_output = Cmd.onecmd(self, line)
            return self.last_cmd_output
Exemplo n.º 41
0
 def onecmd(self, line):
     self.dprint('line:"{0}"'.format(line))
     cmd, arg, line = self.parseline(line)
     func = getattr(self, "hidden_{0}".format(cmd), None)
     try:
         if func:
             self.dprint('Running onecmd func: {0}.hidden_{1}("{2}")'.format(self, cmd, arg))
             return func(arg)
         else:
             self.dprint('Did not find func, running Cmd.onecmd(line="{0}")'.format(line))
             return Cmd.onecmd(self, line)
     except CliError as AE:
         self.eprint("ERROR: " + str(AE))
         return self.onecmd("? " + str(line))
     except SystemExit:
         raise
     except Exception as FE:
         if self.env.simplecli_config.debug:
             print_exc(file=self.stderr)
         self.eprint('\n"{0}": {1}({2})'.format(line, FE.__class__.__name__, str(FE)))
         self.oprint('\n')
Exemplo n.º 42
0
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line = line
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except UnicodeDecodeError as e:
         tui.error("Unicode decoding error. Please check you locale and terminal settings (%s)." % e)
     except UnicodeEncodeError as e:
         tui.error("Unicode encoding error. Please check you locale and terminal settings (%s)." % e)
     except BadUsageException as e:
         tui.error("*** Bad usage ***\n\t%s" % e)
         cmd = line.split(' ')[0]
         self.do_help(cmd)
     except YokadiException as e:
         tui.error("*** Yokadi error ***\n\t%s" % e)
     except IOError as e:
         # We can get I/O errors when yokadi is piped onto another shell commands
         # that breaks.
         print("*** I/O error ***\n\t%s" % e, file=sys.stderr)
     except KeyboardInterrupt:
         print("*** Break ***")
     except Exception as e:
         tui.error("Unhandled exception (oups)\n\t%s" % e)
         print("This is a bug of Yokadi, sorry.")
         print("Send the above message by email to Yokadi developers ([email protected]) to help them make"
               " Yokadi better.")
         cut = "---------------------8<----------------------------------------------"
         print(cut)
         traceback.print_exc()
         print("--")
         print("Python: %s" % sys.version.replace("\n", " "))
         print("SQL Alchemy: %s" % sqlalchemy.__version__)
         print("OS: %s (%s)" % os.uname()[0:3:2])
         print("Yokadi: %s" % yokadi.__version__)
         print(cut)
         print()
Exemplo n.º 43
0
    def onecmd(self, line):
        '''Override onecmd.

        1 - So we don't have to have a do_EOF method.
        2 - So we can strip comments
        3 - So we can track line numbers

        '''
        self.line_num += 1
        if line == 'EOF':
            if Cmd.use_rawinput:
                # This means that we printed a prompt, and we'll want to
                # print a newline to pretty things up for the caller.
                print('')
            return True
        # Strip comments
        comment_idx = line.find('#')
        if comment_idx >= 0:
            line = line[0:comment_idx]
            line = line.strip()
        try:
            return Cmd.onecmd(self, line)
        except ValueError as err:
            return self.handle_exception(err)
Exemplo n.º 44
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except CPUException, e:
         self.stdout.write('CPUException: %s\n' % e)
Exemplo n.º 45
0
Arquivo: main.py Projeto: kedder/exsvn
 def onecmd(self, line):
     try:
         Cmd.onecmd(self, line)
     except ApplicationError, e:
         print "Error occured: %s" % e
Exemplo n.º 46
0
 def openChild(self, childName: cmd.Cmd, arg):
     if arg == '':
         a = childName.onecmd('help')
     else:
         a = childName.onecmd(arg)
     return a
Exemplo n.º 47
0
 def onecmd(self, line):
     try:
         return _Cmd.onecmd(self, line)
     except Exception as error:
         print "%s: %s" % (type(error).__name__, error)
Exemplo n.º 48
0
 def onecmd(self, line):
   try:
     return Cmd.onecmd(self, line)
   except GetoptError as e:
     error(str(e))
Exemplo n.º 49
0
 def onecmd(self, args):
     try:
         return Cmd.onecmd(self, args)
     except Exception:
         traceback.print_exc(self.stdout)
         return False
Exemplo n.º 50
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except CPUException, e:
         self.stdout.write('CPUException: %s\n' % e)
Exemplo n.º 51
0
 def onecmd(self, st):
     try:
         Cmd.onecmd(self, st)
     except Exception as e:
         print(e)
Exemplo n.º 52
0
 def onecmd(self, commands, separator=";"):
     """ load command separate for ; file or string"""
     for command in commands.split(separator):
         Cmd.onecmd(self, command)
Exemplo n.º 53
0
 def onecmd(self, line):
     try:
         return _Cmd.onecmd(self, line)
     except Exception as error:
         print "%s: %s" % (type(error).__name__, error)