Пример #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)
Пример #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)
Пример #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)
Пример #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))
Пример #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))
Пример #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')
Пример #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'
Пример #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'
Пример #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
Пример #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
Пример #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
Пример #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
Пример #13
0
 def onecmd(self, line):
     try:
         ret = Cmd.onecmd(self, line)
         self.session.commit()
         return ret
     except Exception, e:
         print e
         return None
Пример #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
Пример #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
Пример #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
Пример #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)
Пример #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))
Пример #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()
Пример #20
0
 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()
Пример #21
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))
Пример #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)
Пример #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)
Пример #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)
Пример #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
Пример #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
Пример #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
Пример #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)
Пример #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
Пример #30
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)
Пример #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
Пример #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)
Пример #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)
Пример #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
Пример #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)
Пример #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()
Пример #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
Пример #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
Пример #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()
Пример #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
Пример #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')
Пример #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()
Пример #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)
Пример #44
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except CPUException, e:
         self.stdout.write('CPUException: %s\n' % e)
Пример #45
0
 def onecmd(self, line):
     try:
         Cmd.onecmd(self, line)
     except ApplicationError, e:
         print "Error occured: %s" % e
Пример #46
0
 def openChild(self, childName: cmd.Cmd, arg):
     if arg == '':
         a = childName.onecmd('help')
     else:
         a = childName.onecmd(arg)
     return a
Пример #47
0
 def onecmd(self, line):
     try:
         return _Cmd.onecmd(self, line)
     except Exception as error:
         print "%s: %s" % (type(error).__name__, error)
Пример #48
0
 def onecmd(self, line):
   try:
     return Cmd.onecmd(self, line)
   except GetoptError as e:
     error(str(e))
Пример #49
0
 def onecmd(self, args):
     try:
         return Cmd.onecmd(self, args)
     except Exception:
         traceback.print_exc(self.stdout)
         return False
Пример #50
0
 def onecmd(self, line):
     try:
         return Cmd.onecmd(self, line)
     except CPUException, e:
         self.stdout.write('CPUException: %s\n' % e)
Пример #51
0
 def onecmd(self, st):
     try:
         Cmd.onecmd(self, st)
     except Exception as e:
         print(e)
Пример #52
0
 def onecmd(self, commands, separator=";"):
     """ load command separate for ; file or string"""
     for command in commands.split(separator):
         Cmd.onecmd(self, command)
Пример #53
0
 def onecmd(self, line):
     try:
         return _Cmd.onecmd(self, line)
     except Exception as error:
         print "%s: %s" % (type(error).__name__, error)