Пример #1
0
    def get_org(self, username):
        try:
            owner_list = self.cp.getOwnerList(username)
        except Exception as e:
            log.exception(e)
            system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)

        if len(owner_list) == 0:
            system_exit(1, _("%s cannot register with any organizations.") % username)
        else:
            if self.options.org:
                org_input = self.options.org
            elif len(owner_list) == 1:
                org_input = owner_list[0]['key']
            else:
                org_input = six.moves.input(_("Org: ")).strip()
                readline.clear_history()

            org = None
            for owner_data in owner_list:
                if owner_data['key'] == org_input or owner_data['displayName'] == org_input:
                    org = owner_data['key']
                    break
            if not org:
                system_exit(os.EX_DATAERR, _("Couldn't find organization '%s'.") % org_input)
        return org
Пример #2
0
def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
    """
    Get user input with readline editing support.
    """

    sentinel = ''
    if prefill is None:
        prefill = ''
    
    def only_once(text):
        """ generator for startup hook """
        readline.insert_text(text)
        yield
        while True:
            yield

    savedhist = NamedTemporaryFile()
    readline.write_history_file(savedhist.name)
    ctxhistname = ".tl" + ctxkey + "history"
    ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
    try:
        readline.clear_history()
    except AttributeError:
        print "This readline doesn't support clear_history()"
        raise
    
    savedcompleter = readline.get_completer()
    try:
        ulines = uniqify(ctxhistfile)
        readline.read_history_file(ctxhistfile)
        readline.set_completer(HistoryCompleter(ulines).complete)
    except IOError:
        pass

    readline.parse_and_bind('tab: complete')
    saveddelims = readline.get_completer_delims()
    readline.set_completer_delims('') ## No delims. Complete entire lines.
    readline.set_completion_display_matches_hook(match_display_hook)
    gen = only_once(prefill)
    readline.set_startup_hook(gen.next)
    try:
        if oneline:
            edited = raw_input(prompt)
        else:
            print prompt
            edited = "\n".join(iter(raw_input, sentinel))

        if edited.endswith(r'%%'):
            ## Invoke external editor
            edited = external_edit(edited[0:-2])
        return edited
    finally:
        ## Restore readline state 
        readline.write_history_file(ctxhistfile)
        readline.clear_history()
        readline.read_history_file(savedhist.name)
        savedhist.close()
        readline.set_completer(savedcompleter)
        readline.set_completer_delims(saveddelims)
        readline.set_startup_hook()    
Пример #3
0
 def clear_history(self):
     try:
         readline.clear_history()
     except AttributeError:
         len = self.get_max_length()
         readline.set_history_length(0)
         readline.set_history_length(len)
Пример #4
0
    def handle(self, cmd):
        args = cmd.split(' ')
        if args[0] == 'save':
            if len(args) >= 3:
                alias = args[1]
                (host, port) = usc_config.make_addr(args[2:])
                usc_config.save_alias(alias, host, port)
                self.comp.add_to_list("alias", {alias})
        elif args[0] == 'drop':
            if len(args) == 2:
                usc_config.remove_alias(args[1])
        elif args[0] == 'list':
            aliases = usc_config.get_aliases()
            for alias in aliases:
                print(alias + " : " + repr(aliases[alias]))
        elif args[0] == 'connect':
            print("Connecting...")
            c = controller.UscController()
            (host, port) = usc_config.resolve_addr(args[1:])

            readline.write_history_file('.history')
            readline.clear_history()
            # Long call
            c.connect(host, port)
            print("Disconnected.")

            readline.clear_history()
            readline.read_history_file('.history')
            # Done !
            self.refresh()
        elif args[0] == 'quit':
            return True

        return False
Пример #5
0
 def clear_history(self):
     try:
         readline.clear_history()
     except AttributeError:
         len = self.get_max_length()
         readline.set_history_length(0)
         readline.set_history_length(len)
Пример #6
0
 def restore_old_history(self):
     readline.clear_history()
     for line in self._oldHistory:
         if line is None:
             continue
         readline.add_history(line)
     self._oldHistory = []
Пример #7
0
def run_tests():
    global CONSUMER_KEY, CONSUMER_SECRET, SERVER_URL
    CONSUMER_KEY = raw_input("consumer key (anyone): ") or "anyone"
    CONSUMER_SECRET = raw_input("consumer secret (anyone): ") or "anyone"
    SERVER_URL = raw_input("server base url (http://www.khanacademy.org): ") \
        or "http://www.khanacademy.org"

    # It's a bit annoying for key/secret to be in readline history
    readline.clear_history()
    print

    get_request_token()
    if not REQUEST_TOKEN:
        print "Did not get request token."
        return

    get_access_token()
    if not ACCESS_TOKEN:
        print "Did not get access token."
        return

    while(True):
        try:
            get_api_resource()
        except EOFError:
            print
            break
        except Exception, e:
            print "Error: %s" % e
 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint("%s %s" % (str(idx).rjust(numLen),
                                     readline.get_history_item(idx)))
Пример #9
0
def run_tests():
    global CONSUMER_KEY, CONSUMER_SECRET, SERVER_URL
    CONSUMER_KEY = raw_input("consumer key (anyone): ") or "anyone"
    CONSUMER_SECRET = raw_input("consumer secret (anyone): ") or "anyone"
    SERVER_URL = raw_input("server base url (http://www.khanacademy.org): ") or "http://www.khanacademy.org"

    # It's a bit annoying for key/secret to be in readline history
    readline.clear_history()
    print

    get_request_token()
    if not REQUEST_TOKEN:
        print "Did not get request token."
        return

    get_access_token()
    if not ACCESS_TOKEN:
        print "Did not get access token."
        return

    while(True):
        try:
            get_api_resource()
        except EOFError:
            print
            break
        except urllib2.HTTPError, e:
            print 'Error: %s' % e
            # Also print the response body in case it has useful information.
            print e.read()
        except Exception, e:
            print "Error: %s" % e
Пример #10
0
def prompt(honesty, included, excluded):
    if included:
        cprint(_("Files that will be submitted:"), "green")
        for file in included:
            cprint("./{}".format(file), "green")
    else:
        raise Error(
            _("No files in this directory are expected for submission."))

    # Files that won't be submitted
    if excluded:
        cprint(_("Files that won't be submitted:"), "yellow")
        for other in excluded:
            cprint("./{}".format(other), "yellow")

    # Prompt for honesty
    if not honesty:
        return True

    if honesty is True:
        honesty = _("Keeping in mind the course's policy on "
                    "academic honesty, are you sure you want to "
                    "submit these files?")

    readline.clear_history()

    try:
        answer = input(f"{_(honesty)} ({_('yes/no')}) ")
    except EOFError:
        answer = None
        print()
    if not answer or not re.match(f"^\s*(?:{_('y|yes')})\s*$", answer, re.I):
        return False

    return True
Пример #11
0
def clear_screens(user_input: 'UserInput', window: 'TxWindow',
                  settings: 'Settings', queues: 'QueueDict') -> None:
    """Clear/reset screen of Source, Destination, and Networked Computer.

    Only send an unencrypted command to Networked Computer if traffic
    masking is disabled.

    With clear command, sending only the command header is enough.
    However, as reset command removes the ephemeral message log on
    Receiver Program, Transmitter Program must define the window to
    reset (in case, e.g., previous window selection command packet
    dropped, and active window state is inconsistent between the
    TCB programs).
    """
    clear = user_input.plaintext.split()[0] == CLEAR

    command = CLEAR_SCREEN if clear else RESET_SCREEN + window.uid
    queue_command(command, settings, queues)

    clear_screen()

    if not settings.traffic_masking:
        pt_cmd = UNENCRYPTED_SCREEN_CLEAR if clear else UNENCRYPTED_SCREEN_RESET
        packet = UNENCRYPTED_DATAGRAM_HEADER + pt_cmd
        queue_to_nc(packet, queues[RELAY_PACKET_QUEUE])

    if not clear:
        readline.clear_history()
        reset_terminal()
Пример #12
0
def main():
    #TODO: write description
    desc = "TODO"
    parser = argparse.ArgumentParser(prog="refimgdb.py", description=desc)

    parser.add_argument('-action',
                        action='store',
                        dest='action',
                        type=str,
                        help='Action to perform (get, update)')
    parser.add_argument('-fid',
                        action='store',
                        dest='fid',
                        type=int,
                        help='FID of image')
    parser.add_argument('-date',
                        action='store',
                        dest='date',
                        type=str,
                        help='Date of image')
    parser.add_argument('-column',
                        action='store',
                        dest='column',
                        type=str,
                        help='Database column')
    parser.add_argument('-value',
                        action='store',
                        dest='value',
                        type=str,
                        help='Update column with value')

    args = parser.parse_args()

    db = openDB()

    # Check if command lines arguements used
    if (args.action is None and args.fid is None and args.date is None
            and args.column is None and args.value is None):
        # Create variable for user exiting
        exited = False
        while exited == False:
            exited = inputPrompt(db)
            readline.clear_history()
    # If command line argument, perform actions accordingly
    else:
        # Check if user specified a usable action
        possible_action = ['get', 'update']
        if (args.action in possible_action) is False:
            print 'Error: action not possible'
            print parser.print_help()
            sys.exit(1)
        else:
            if args.action == 'get':
                cursor = queryFID(db, args.fid, args.date, args.column)
                print_query(cursor)
            elif args.action == 'update':
                updateFID(db, args.fid, args.date, args.column, args.value)

    db.close()
    sys.exit(0)
Пример #13
0
 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - int(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print("CloudMonkey history cleared")
         return
     elif len(historyArg
              ) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(int(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in range(startIdx, endIdx):
         self.monkeyprint(
             "%s %s" %
             (str(idx).rjust(numLen), readline.get_history_item(idx)))
Пример #14
0
def run_classic_shell(globals, locals, first_time=[True]):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
        first_time.pop()
    else:
        banner = ""

    ns = SetPropagatingDict([locals, globals], locals)

    from pudb.settings import get_save_config_path
    from os.path import join
    hist_file = join(
            get_save_config_path(),
            "shell-history")

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)

    cons.interact(banner)

    if HAVE_READLINE:
        readline.write_history_file(hist_file)
Пример #15
0
    def get_environment(self, owner_key):
        environment_list = []
        try:
            if self.cp.supports_resource('environments'):
                environment_list = self.cp.getEnvironmentList(owner_key)
            elif self.options.environment:
                system_exit(os.EX_UNAVAILABLE, _("Environments are not supported by this server."))
        except Exception as e:
            log.exception(e)
            system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)

        environment = None
        if len(environment_list) > 0:
            if self.options.environment:
                env_input = self.options.environment
            elif len(environment_list) == 1:
                env_input = environment_list[0]['name']
            else:
                env_input = six.moves.input(_("Environment: ")).strip()
                readline.clear_history()

            for env_data in environment_list:
                # See BZ #978001
                if (env_data['name'] == env_input or
                   ('label' in env_data and env_data['label'] == env_input) or
                   ('displayName' in env_data and env_data['displayName'] == env_input)):
                    environment = env_data['name']
                    break
            if not environment:
                system_exit(os.EX_DATAERR, _("Couldn't find environment '%s'.") % env_input)

        return environment
Пример #16
0
 def uninit_completer(self):
     try:
         import readline
         readline.set_completer()
         readline.clear_history()
     except:
         pass
Пример #17
0
def run(func, *args, **kwargs):
    """pdb hook: invokes pdb on exceptions in python.

    The function func is called, with arguments args and
    kwargs=kwargs.  If this func raises an exception, pdb is invoked
    on that frame.  Upon exit from pdb, return to python normally."""
    # save history
    old_hist = _get_history()
    old_hist_start = readline.get_current_history_length()+1

    try:
        return func(*args, **kwargs)
    except Exception as e:
        _add_history(_run_history)


        t, value, tb = sys.exc_info()
        sys.__excepthook__(t, value, tb)
        frame = sys.exc_info()[2]
        #tb = e.tb_frame
        pdb.post_mortem(tb)
        del frame   # the docs warn to avoid circular references.
        del t, value, tb

        _run_history[:] = _get_history(first=old_hist_start)
    readline.clear_history()
    _restore_history(old_hist)
    print old_hist
Пример #18
0
    def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context =
            {}):
        """Launch a subshell.

        The doc string of the cmdloop() method explains how shell histories and
        history files are saved and restored.

        The design of the _ShellBase class encourage launching of subshells through
        the subshell() decorator function. Nonetheless, the user has the option
        of directly launching subshells via this method.

        Arguments:
            shell_cls: The _ShellBase class object to instantiate and launch.
            args: Arguments used to launch this subshell.
            prompt: The name of the subshell. The default, None, means
                to use the shell_cls.__name__.
            context: A dictionary to pass to the subshell as its context.

        Returns:
            'root': Inform the parent shell to keep exiting until the root shell
                is reached.
            'all': Exit the the command line.
            False, None, or anything that are evaluated as False: Inform the
                parent shell to stay in that parent shell.
            An integer indicating the depth of shell to exit to. 0 = root shell.
        """
        # Save history of the current shell.
        readline.write_history_file(self.history_fname)

        prompt = prompt if prompt else shell_cls.__name__
        mode = _ShellBase._Mode(
                shell = self,
                cmd = cmd,
                args = args,
                prompt = prompt,
                context = context,
        )
        shell = shell_cls(
                batch_mode = self.batch_mode,
                debug = self.debug,
                mode_stack = self._mode_stack + [ mode ],
                pipe_end = self._pipe_end,
                root_prompt = self.root_prompt,
                stdout = self.stdout,
                stderr = self.stderr,
                temp_dir = self._temp_dir,
        )
        # The subshell creates its own history context.
        self.print_debug("Leave parent shell '{}'".format(self.prompt))
        exit_directive = shell.cmdloop()
        self.print_debug("Enter parent shell '{}': {}".format(self.prompt, exit_directive))

        # Restore history. The subshell could have deleted the history file of
        # this shell via 'history clearall'.
        readline.clear_history()
        if os.path.isfile(self.history_fname):
            readline.read_history_file(self.history_fname)

        if not exit_directive is True:
            return exit_directive
Пример #19
0
    def get_meta(prompt, default, default_list):
        default_count = 0
        if default_list:
            if not default:
                count = len(default_list)
                if count == 0:
                    default = ''
                else:
                    if type(default_list[0]) is str:
                        default = default_list[0]
                    else:
                        default = default_list[0][0]
                    default_count = count - 1

            readline.clear_history()
            default_list.reverse()
            for d in default_list:
                if type(d) is str:
                    readline.add_history(d)
                else:
                    readline.add_history(d[0])

        if default_count > 0:
            full_prompt = ('{} [{}](+ {} more): '.
                    format(prompt, default, default_count))
        else:
            full_prompt = ('{} [{}]: '.
                    format(prompt, default))

        result = input(full_prompt)
        if result == '':
            return default
        else:
            return result
 def i(self):
   """
   Enter in madx command line
   r.i()
   """
   readline.parse_and_bind("tab: complete")
   fn1=home+'/.history_madx'
   fn2=home+'/.ipython/history'
   os.system("touch " + fn1)
   os.system("touch " + fn2)
   print "Type Ctrl-D to enter ipython"
   cmd=''
   readline.clear_history()
   readline.read_history_file(fn1)
   print 'X: ==> '
   try:
     while( 1):
       cmd=cmd+re.sub('\!.*','',raw_input())
       if cmd.endswith(';'):
         self.p(cmd)
         cmd=''
         print 'X: ==> '
   except EOFError:
     pass
   readline.write_history_file(fn1)
   readline.clear_history()
   readline.read_history_file(fn2)
   print "Type madx() to enter MadX"
Пример #21
0
 def _save_history(self, history_file):
     """
     Save the commandline history to the readline history provided
     + Clear the history buffer
     """
     readline.write_history_file(os.path.join(MODULE_LOCATION, history_file))
     readline.clear_history()  
Пример #22
0
def pudb_shell(_globals, _locals):
    """
    This example shell runs a classic Python shell. It is based on
    run_classic_shell in pudb.shell.

    """
    # Many shells only let you pass in a single locals dictionary, rather than
    # separate globals and locals dictionaries. In this case, you can use
    # pudb.shell.SetPropagatingDict to automatically merge the two into a
    # single dictionary. It does this in such a way that assignments propogate
    # to _locals, so that when the debugger is at the module level, variables
    # can be reassigned in the shell.
    from pudb.shell import SetPropagatingDict
    ns = SetPropagatingDict([_locals, _globals], _locals)

    try:
        import readline
        import rlcompleter
        HAVE_READLINE = True
    except ImportError:
        HAVE_READLINE = False

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)
    cons.interact("Press Ctrl-D to return to the debugger")
Пример #23
0
    def set_context(self, name):
        """Set the current history context.

        This swaps in a new history context by loading
        the history from the contexts filename.  The
        old context's history is saved first.
        """

        if name not in self.contexts:
            raise ValueError("Invalid history context: %s" % name)

        if self.current:
            if name == self.current.name:
                return
            self.save()

        self.current = self.contexts[name]

        try:
            readline.clear_history()
            if self.current.obj:
                with open(self.current.filename, "r") as f:
                    lines = pickle.load(f)

                for line in lines:
                    readline.add_history(line)

            else:
                readline.read_history_file(self.current.filename)
        except IOError:
            pass
Пример #24
0
    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
            readline.clear_history()
            map(readline.add_history, self.history)

        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix,))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code,)
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e,)
Пример #25
0
    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
Пример #26
0
    def getInput(self):
        out = None
        if self._default == None:
            self._default = datetime.datetime.now(dateutil.tz.tzlocal())
        readline.clear_history()

        # put the default value into history
        readline.add_history(self._formatDate(self._default))

        # try to complete during typing.
        readline.set_completer_delims('\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.comp)

        # get user input until it's acceptable
        while out == None:
            inp = input(self._display + " [{}]: "
                        .format(self._formatDate(self._default)))
            if inp == "?":
                self.printSpec()
            else:
                try:
                    out = self.tryParse(inp.strip(), self._default)
                except Exception as e:
                    # although the value is not acceptable, give user
                    # a chance to modify it.
                    hist = inp.strip()
                    if len(hist) > 0:
                        readline.add_history(inp.strip())
                    self.printSpec()

        readline.clear_history()
        readline.set_completer()
        # print(">> {}: {}".format(self._display, out.strftime("%Y/%m/%d %H:%M")))
        return out
Пример #27
0
    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
Пример #28
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        import readline
        readline.clear_history()
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                        except KeyboardInterrupt:
                            line = '\r\n'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                self.cleartimer()
                self.mytimer(CLI_TIMEOUT_SECONDS)
                if any(x in line for x in banned_characters):
                    print u'错误的命令'.encode("utf-8")
                else:
                    line = self.precmd(line)
                    stop = self.onecmd(line)
                    stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #29
0
 def load_history(self):
     try:
         import readline
         readline.clear_history()
         readline.set_history_length(MAX_HISTORY_SIZE)
         readline.read_history_file(self.history_file)
     except (ImportError, AttributeError, IOError):
         pass
Пример #30
0
    def raw_input_no_history(self, prompt):
        if self.filelines:
            return self.filelines.pop(0)
        else:
            input = input(prompt)
            readline.clear_history()

            return input
Пример #31
0
    def raw_input_no_history(self, prompt):
        if self.filelines:
            return self.filelines.pop(0)
        else:
            input = raw_input(prompt)
            readline.clear_history()

            return input
Пример #32
0
 def getInput(self):
     readline.set_completer_delims('\n;')
     readline.parse_and_bind("tab: complete")
     readline.set_completer(self.comp)
     r = super().getInput()
     readline.set_completer()
     readline.clear_history()
     return r
Пример #33
0
 def history_pause(self):
     """Store readline history to local history storage, and clear history"""
     self._history_storage = []
     for i in range(readline.get_current_history_length()):
         item = readline.get_history_item(i)
         if item is not None:
             self._history_storage.append(item)
     readline.clear_history()
Пример #34
0
def main():
    PARSER = optparse.OptionParser( usage=USAGE, description=__doc__ )

    PARSER.add_option("-d",
        dest = "device",
        action = "store",
        type = "string",
        help = "serial port device",
        default = DEFAULT_DEVICE,
    )
 
    PARSER.add_option("-e",
        dest = "erase",
        action = "store_true",
        help = "erase flash",
        default = False 
    )

    PARSER.add_option("-p",
        dest = "program",
        action = "store_true",
        help = "and program files",
        default = False
    )
    
    (options, args) = PARSER.parse_args()

    if not options.device:
        PARSER.error("No device assigned")
    
    ARMPIT = Armpit( options.device )
    ARMPIT.syncPrompt()
    #ARMPIT.showInfo()

    if options.erase or options.program:
        # flash operation
        ARMPIT.unlockFlash()
        if options.erase:
            ARMPIT.eraseFlash()
        if options.program:
            if not args:
                sys.stderr.write( "no file to be programed\n" )
                sys.exit(1)
            # program files
            ARMPIT.preProgram()
            for filename in args:
                if os.path.isfile( filename ):
                    ARMPIT.programFlash( filename )

    elif args:
        # eval files
        for filename in args:
            if os.path.isfile( filename ):
                ARMPIT.evalFile( filename )
    else:
        readline.clear_history()
        # interactive mode
        ARMPIT.enterRepl()
Пример #35
0
def main():
    PARSER = optparse.OptionParser(usage=USAGE, description=__doc__)

    PARSER.add_option(
        "-d",
        dest="device",
        action="store",
        type="string",
        help="serial port device",
        default=DEFAULT_DEVICE,
    )

    PARSER.add_option("-e",
                      dest="erase",
                      action="store_true",
                      help="erase flash",
                      default=False)

    PARSER.add_option("-p",
                      dest="program",
                      action="store_true",
                      help="and program files",
                      default=False)

    (options, args) = PARSER.parse_args()

    if not options.device:
        PARSER.error("No device assigned")

    ARMPIT = Armpit(options.device)
    ARMPIT.syncPrompt()
    #ARMPIT.showInfo()

    if options.erase or options.program:
        # flash operation
        ARMPIT.unlockFlash()
        if options.erase:
            ARMPIT.eraseFlash()
        if options.program:
            if not args:
                sys.stderr.write("no file to be programed\n")
                sys.exit(1)
            # program files
            ARMPIT.preProgram()
            for filename in args:
                if os.path.isfile(filename):
                    ARMPIT.programFlash(filename)

    elif args:
        # eval files
        for filename in args:
            if os.path.isfile(filename):
                ARMPIT.evalFile(filename)
    else:
        readline.clear_history()
        # interactive mode
        ARMPIT.enterRepl()
Пример #36
0
    def authenticate(self, username, password, user_prompt, pw_prompt):
        if not username:
            username = six.moves.input(user_prompt).strip()
            readline.clear_history()

        if not password:
            password = getpass.getpass(prompt=pw_prompt)

        return UserCredentials(username, password)
Пример #37
0
 def history_command(self, args):
     if args == '':
         len = readline.get_current_history_length()
         for index in range(1, len + 1):
             print('%s' % readline.get_history_item(index))
     elif args == '--clear':
         readline.clear_history()
     else:
         self.invalid_operation('history', args)
Пример #38
0
    def __init__(self):
        self.config = ConfigParser().read(self.MASTER_PATH)
        self._loaded_connectors = {}

        readline.clear_history()
        readline.read_history_file(self.MASTER_HISTORY)
        readline.set_history_length(100)

        atexit.register(lambda path: self.config.write(path), self.MASTER_PATH)
Пример #39
0
 def choose(self):
     while True:
         self.display()
         selection = six.moves.input("? ").strip()
         readline.clear_history()
         try:
             return self._get_item(selection)
         except InvalidChoiceError:
             self.display_invalid()
Пример #40
0
        def startup_hook():
            readline.insert_text(pre_fill)

            if history is not None:
                readline.clear_history()
                _history = (history
                            if isinstance(history, list) else [str(history)])
                for line in _history:
                    readline.add_history(str(line))
Пример #41
0
 def choose(self):
     while True:
         self.display()
         selection = six.moves.input("? ").strip()
         readline.clear_history()
         try:
             return self._get_item(selection)
         except InvalidChoiceError:
             self.display_invalid()
Пример #42
0
    def authenticate(self, username, password, user_prompt, pw_prompt):
        if not username:
            username = six.moves.input(user_prompt).strip()
            readline.clear_history()

        if not password:
            password = getpass.getpass(prompt=pw_prompt)

        return UserCredentials(username, password)
Пример #43
0
    def do_history(self, args):
        """
        This method handles all tasks related to management of history of commands

        """
        self.gLogging.debug("do_history invoked")
        description = "work with commands history"
        try:
            #import argcomplete
            parser = argparse.ArgumentParser(prog="history", add_help=True, epilog=self.epilog, description=description, usage="history <command> [<args>]")
            subparsers = parser.add_subparsers()

            clear_parser = subparsers.add_parser('clear', description="clear history", usage="history clear <args>")
            clear_parser.set_defaults(which='clear')
            clear_parser.add_argument('-Y', '--yes', action='store_true', required=True, help="confirm")

            show_parser = subparsers.add_parser('show', description="show history", usage="history show") #, aliases=['s']
            show_parser.set_defaults(which='show')

            rem_parser = subparsers.add_parser('run', description="run command again", usage="history run <args>")
            rem_parser.set_defaults(which='run')
            rem_parser.add_argument('-c', '--command', type=int, required=True, help="command number")

            find_parser = subparsers.add_parser('find', description="find command", usage="history find <args>")
            find_parser.set_defaults(which='find')
            find_parser.add_argument('-c', '--command', type=str, required=True, help="command substring")

            #completer = argcomplete.CompletionFinder(parser)
            #readline.set_completer_delims("")
            #readline.set_completer(completer.rl_complete)
            #readline.parse_and_bind("tab: complete")

            choice = vars(parser.parse_args(args.split()))
            if len(args) == 0:
                parser.print_help()
            elif choice['which'] == 'clear':
                if choice['yes']:
                    readline.clear_history()
                else:
                    self.gLogging.show("skipped.. ")
            elif choice['which'] == 'show':
                for i in range(readline.get_current_history_length()):
                    print(i+1, readline.get_history_item(i + 1))
            elif choice['which'] == 'run':
                self.onecmd(readline.get_history_item(choice['command']))
            elif choice['which'] == 'find':
                for i in range(readline.get_current_history_length()):
                    if choice['command'] in readline.get_history_item(i + 1):
                        print(i+1, readline.get_history_item(i + 1))
            else:
                parser.print_help()

        except SystemExit:
            pass
        except Exception:
            self.gLogging.error("cannot parse given arguments")
Пример #44
0
 def init_history(self, histfile):
     readline.parse_and_bind("tab: complete")
     if hasattr(readline, "read_history_file"):
         try:
             readline.clear_history()
             readline.read_history_file(histfile)
         except IOError:
             pass
         from atexit import register
         register(self.save_history, histfile)
Пример #45
0
    def do_clear_history(self):
        """Clears the history of previously used commands from this shell"""
        if not AUTOCOMPLETE_ENABLED:  # pragma: no cover
            self.info("Command completion disabled.")
            return

        # We just clear the current history buffer. When the shell terminates
        # it should write the history to the history file, which should write
        # out an empty history file with maybe just an 'exit' command in it
        readline.clear_history()
Пример #46
0
 def _prompt_for_environment(self):
     """
     By breaking this code out, we can write cleaner tests
     """
     if self.cp.has_capability(MULTI_ENV):
         environment = input(_("Environments: ")).replace(" ", "")
     else:
         environment = input(_("Environment: ")).strip()
     readline.clear_history()
     return environment or self._prompt_for_environment()
Пример #47
0
 def do_note(self, text):
     '''Add text to list of notes.'''
     if not text:
         readline.clear_history()
         try:
             text = raw_input(self.IN_PROMPT)
         except KeyboardInterrupt:
             print
             return
     self.job.notes.append(text)
Пример #48
0
def _i(prompt=''):
    try:
        res = input(prompt)
    except KeyboardInterrupt:
        _p("\033[2J\033[1;1H")
        exit()

    readline.clear_history()

    return res
Пример #49
0
    def hcl():
        """Clear readline history."""
        try:
            clear = raw_input("Clear history? [y|N]: ")
            if clear in ('y', 'Y', 'yes', 'Yes'):
                import readline
                readline.clear_history()

        except EOFError:
            pass
Пример #50
0
    def init_interact(self):
        """Start Interacting with an active session"""
        readline.clear_history()
        readline.set_completer(self.tab_complete)
        readline.parse_and_bind('tab: complete')

        command_modules = self.server.get_modules(self.type)
        cmd = "picture"
        cmd_data = {"cmd": cmd, "args": ""}
        file_name = command_modules[cmd].run(self, cmd_data)
        return file_name
Пример #51
0
def read_path(question=None, allow_files=True, allow_folders=False, history_key=None):
    """
    Read a path, providing retry capabilities and auto-completion

    :param question:            What question to display to the user. Optional, default None
    :type question:             str|None
    :param allow_files:         Do we want a file ? Optional, default True
    :type allow_files:          bool
    :param allow_folders:       Do we want a folder ? Optional, default False
    :type allow_folders:        bool
    :param history_key:         Which history we should use. Should math [a-z]+ format. Optional, default None
    :type history_key:          str|None
    :return:                    The selected file
    :rtype:                     str
    """

    # FIXME LATER: improve One choice with slashes

    use_readline = can_use_readline()
    if use_readline:
        import readline

        def path_completer(text, state):
            readline.get_line_buffer().split()
            expanded_text = os.path.expanduser(text)
            tmp = [x for x in glob.glob(os.path.expanduser(text) + '*')][state]
            if tmp:
                tmp = text + tmp[len(expanded_text):]
            return tmp

        script_path = os.path.dirname(os.path.abspath(__file__))
        project_path = os.path.abspath(os.path.join(script_path, "..", ".."))
        hist_dir = os.path.join(project_path, "tmp", "cmd_history")
        hist_file = os.path.join(hist_dir, history_key) if history_key else None
        if history_key is not None:
            if not os.path.exists(hist_dir):
                os.makedirs(hist_dir)
            if os.path.exists(hist_file):
                readline.read_history_file(hist_file)

        old_completer = readline.get_completer_delims()
        readline.set_completer_delims('\t')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(path_completer)
        try:
            return simple_read_path(question, allow_files, allow_folders)
        finally:
            readline.set_completer(None)
            readline.set_completer_delims(old_completer)
            if history_key:
                readline.write_history_file(hist_file)
                readline.clear_history()
    else:
        return simple_read_path(question, allow_files, allow_folders)
Пример #52
0
def history_reinit(data):
    # used by 'reauth', user name is in the data dict.
    global history_file
    if history_file:
        try:
            readline.write_history_file(history_file)
        except Exception, e:
            if command.bigsh.description:
                print 'history_reinit: %s: failed to save:' % history_file, e
        readline.clear_history()
        history_file = None
Пример #53
0
def load_history(fname=None, clear=True):
    global history_file
    if not fname: fname = history_file
    if clear: readline.clear_history()
    try:
        fname = expand_path(fname)
        readline.read_history_file(fname)
        history_file = os.path.abspath(fname)
        if verbose: puts('INFO: load history from', history_file, file=err)
    except:
        pass
Пример #54
0
 def preloop(self):
     try:
         import readline
         readline.clear_history()
         if os.path.exists(config.historyfile):
             readline.read_history_file(config.historyfile)
         self.old_completers = readline.get_completer_delims()
         readline.set_completer_delims(
             re.sub(r'-|:|/', '', self.old_completers))
     except ImportError:
         pass
Пример #55
0
 def __enter__(self):
     self._old_history = [
         readline.get_history_item(idx)
         for idx in range(readline.get_current_history_length())
     ]
     self._old_complete = readline.get_completer()
     readline.set_completer_delims(' \t')
     readline.set_history_length(1000)
     readline.clear_history()
     readline.read_history_file(self.histfile)
     readline.parse_and_bind('tab: complete')
Пример #56
0
def histsave(f, histfile="./.save_history"):
    readline.clear_history()
    try:
        readline.read_history_file(histfile)
        h_len = readline.get_current_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        h_len = 0

    readline.add_history(f)
    readline.write_history_file(histfile)
Пример #57
0
def prompt_for_auth_token():
    """
    Prompts for cached token from the user. Reads the token stdin keyed in by the user
    :return: cached token
    """
    readline.clear_history()

    try:
        return input(AUTH_TOKEN_PROMPT).strip()
    except EOFError:
        return ''
Пример #58
0
 def _get_username_and_password(username, password):
     """
     Safely get a username and password from the tty, without echoing.
     if either username or password are provided as arguments, they will
     not be prompted for.
     """
     while not username:
         username = input(_("Username: "******"Password: "))
     return username.strip(), password.strip()
Пример #59
0
    def interact(self):
        """Interact With An Active Session!"""

        try:
            readline.clear_history()
            readline.set_completer(self.tab_complete)
            readline.parse_and_bind('tab: complete')
        except:
            h.info_warning(
                "Readline Not Installed, Tab Completion Not Supported!")

        command_modules = self.server.get_modules(self.type)
        while 1:
            try:

                raw = raw_input(self.get_handle())
                if not raw or raw.replace(" ", "") == "":
                    continue
                cmd = raw.split()[0]
                cmd_data = {"cmd": cmd, "args": raw[len(cmd) + 1:]}

                if self.needs_refresh:

                    pass
                elif cmd == "Exit":
                    self.disconnect(True)
                    return
                elif cmd == "back" and self.server.is_multi:
                    return
                elif cmd == "Help":
                    self.show_commands()
                elif cmd in command_modules.keys():
                    command_modules[cmd].run(self, cmd_data)
                elif cmd in self.server.modules_local.keys():
                    self.server.modules_local[cmd].run(self, cmd_data)
                else:
                    try:
                        result = self.send_command(cmd_data)
                        if result:
                            print result.rstrip()
                    except KeyboardInterrupt:
                        self.send_command({"cmd": "killtask"})
            except KeyboardInterrupt:
                try:
                    print ""
                    if readline.get_line_buffer():
                        continue
                except:
                    pass
                self.disconnect(True)
                return
            except Exception as e:
                print e