Example #1
0
 def savehist():
     try:
         global histfile
         readline.write_history_file(histfile)
         print >>sys.stderr, "    * readline history"
     except:
         print 'Unable to save Python command history'
Example #2
0
	def interactive(self):
		try:
			readline.read_history_file(Debugger.HISTORY_FILE)
		except IOError:
			pass
		cpu = self.cpu
		try:
			while True:
				cmd,args = self.prompt()
				if cmd in 'xq':
					return
				elif cmd == 's':
					cpu.step()
				elif cmd == 'k':
					self.stack(args)
				elif cmd == 'b':
					self.breakpoint(args)
				elif cmd == 'r':
					self.run()
				elif cmd == 'ret':
					self.runUntilRet()
				elif cmd == '?':
					self.evalPrint(args)
				elif cmd == 'l':
					self.listSource(args)
				else:
					print 'Unknown command! (%s)' % cmd
		finally:
			readline.write_history_file(Debugger.HISTORY_FILE)
Example #3
0
def run_classic_shell(locals, globals, first_time):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
    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")
        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)
Example #4
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()  
Example #5
0
    def main_loop(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.rl_completer_safe)
        #print 'delims: ', repr(readline.get_completer_delims())

        hist_file = os.path.expanduser("~/.qadmin_history")
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

        print "Use 'show help;' to see available commands."
        while 1:
            try:
                ln = self.line_input()
                self.exec_string(ln)
            except KeyboardInterrupt:
                print
            except EOFError:
                print
                break
            self.reset_comp_cache()

        try:
            readline.write_history_file(hist_file)
        except IOError:
            pass
Example #6
0
 def do_exit(self, arg):
     '''Quit KED Password Manager'''
     readline.write_history_file(self.histfile)
     if self.modified:
         self.tryToSave()
     self.printMessage(_("Exiting."))
     sys.exit(0)
Example #7
0
    def run_shell(self):
        do_readline = sys.stdin.isatty() and ('-', sys.stdin) in self.files
        if do_readline and os.path.exists(os.path.expanduser('~/.fsh_history')):
            readline.read_history_file(os.path.expanduser('~/.fsh_history'))
            for file in ('/etc/inputrc', os.path.expanduser('~/.inputrc')):
                if os.path.exists(file):
                    with open(file) as fd:
                        readline.parse_and_bind(fd.read())

        while self.files:
            self.curfile, self.curfd, self.curline = self.files[0]
            self.files = self.files[1:]
            if self.verbose:
                print "%s(Now processing %s)" % (self.ps4, self.curfile)
            try:
                while True:
                    line = self.get_input()
                    if not line:
                        break
                    if self.verbose:
                        print '%s%s (%s, line %d)' % (self.ps4, line, self.curfile, self.curline)
                    self.parse_and_run(line)

            except:
                if do_readline:
                    readline.write_history_file(os.path.expanduser('~/.fsh_history'))
                raise

        if do_readline:
            readline.write_history_file(os.path.expanduser('~/.fsh_history'))
Example #8
0
 def write_history():
     try:
         readline.write_history_file(history)
     except (FileNotFoundError, PermissionError):
         # home directory does not exist or is not writable
         # https://bugs.python.org/issue19891
         pass
def SaveInteractiveSession(filename='interactiveSession.py',path=output_dir): 
    """
    Save the interactive session
    
    Input:
     - *filename*: [default = interactiveSession.py'] (string)
     - *path*: (string)
    """
    if not _IsReadline:
        print("Error: install 'readline' first")
    elif _IsReadline:
        historyPath = os.path.join(path,filename)
        if not os.path.exists(path):       
            os.makedirs(directory)        
        
        readline.write_history_file(historyPath)
        file_in = open(historyPath,'r')
        history_list = file_in.readlines()
        n_import_statement = 0
        for command in history_list:            
            if 'import' in command and 'stochpy' in command:
               n_import_statement +=1
   
        n=0
        file_out = open(historyPath,'w')
        for command in history_list:
            if 'import' in command and 'stochpy' in command:      
               n+=1
            if n==n_import_statement:    
                file_out.write(command)
        file_out.close()
        print("Info: Interactive session successfully saved at {0:s}".format(historyPath) )
        print("Info: use 'ipython {0:s} to restart modeling with this interactive session".format(filename) )
Example #10
0
 def cleanup( self ):
     """Write readline history and clean up resources"""
     debugOut( "writing command history" )
     try:
         readline.write_history_file( self.historyfilename )
     except:
         print("SHELL: Unable to save command history")
Example #11
0
    def do_exit(self, line='', i=0):
        """Exit from PyRAF and then Python"""
        if self.debug>1: self.write('do_exit: %s\n' % line[i:])

        # write out history - ignore write errors
        hfile = os.getenv('HOME','.')+os.sep+'.pyraf_history'
        hlen = 1000 # High default.  Note this setting itself may cause
                    # confusion between this history and the IRAF history cmd.
        try:
            hlen = int(iraf.envget('histfilesize'))
        except (KeyError, ValueError):
            pass
        try:
            import readline
            readline.set_history_length(hlen)  # hlen<0 means unlimited
            readline.write_history_file(hfile) # clobber any old version
        except (ImportError, IOError):
            pass

        # any irafinst tmp files?
        irafinst.cleanup() # any irafinst tmp files?

        # graphics
        wutil.closeGraphics()

        # leave
        raise SystemExit
Example #12
0
def save_history(historyPath=historyPath):
    try:
        import readline
    except ImportError:
        print "Module readline not available."
    else:
        readline.write_history_file(historyPath)
Example #13
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()    
Example #14
0
def quits(showlogo=True):
    """ Exit the program. """
    if has_readline:
        readline.write_history_file(g.READLINE_FILE)
        util.dbg("Saved history file")

    cache.save()

    screen.clear()
    msg = logo(c.r, version=__version__) if showlogo else ""
    msg += util.F("exitmsg", 2)

    if config.CHECKUPDATE.get and showlogo:

        try:
            url = "https://raw.githubusercontent.com/mps-youtube/mps-youtube/master/VERSION"
            v = urlopen(url, timeout=1).read().decode()
            v = re.search(r"^version\s*([\d\.]+)\s*$", v, re.MULTILINE)

            if v:
                v = v.group(1)

                if v > __version__:
                    msg += "\n\nA newer version is available (%s)\n" % v

        except (URLError, HTTPError, socket.timeout):
            util.dbg("check update timed out")

    screen.msgexit(msg)
Example #15
0
File: repl.py Project: JoM-Lab/JoM
def main(debug):
    print("type exit to quit repl")
    if os.path.exists(HISTORY):
        readline.read_history_file(HISTORY)
    q = Query(debug=debug)
    try:
        while True:
            l = input("> ").lstrip("/")
            if not l:
                continue
            elif l == "exit":
                break
            else:
                try:
                    res = q.query("repl", l)
                except Exception as e:
                    print(str(e))
                    traceback.print_tb(e.__traceback__)
                    continue
                if res.message:
                    print(res.message.strip())
                elif res.fileobj:
                    print(res.fileobj)
    except EOFError:
        return
    finally:
        readline.write_history_file(HISTORY)
Example #16
0
 def __del__(self):
     if readline:
         if self._historyfile:
             try:
                 readline.write_history_file(self._historyfile)
             except:
                 pass
Example #17
0
 def interact(self, cmd=None):
     _reset_readline()
     if cmd and isinstance(cmd, BaseCommands):
         self.push_command(cmd)
     if readline:
         oc = readline.get_completer()
         readline.set_completer(self._rl_completer)
     try:
         try:
             while 1:
                 ui = self._cmd._ui
                 try:
                     line = ui.user_input()
                     if not line:
                         continue
                     while self.feed(line+"\n"):
                         line = ui.more_user_input()
                 except EOFError:
                     self._cmd._print()
                     self.pop_command()
         except (CommandQuit, CommandExit): # last command does this
             pass
     finally:
         if readline:
             readline.set_completer(oc)
             if self._historyfile:
                 try:
                     readline.write_history_file(self._historyfile)
                 except:
                     pass
Example #18
0
def prompt(jep):
    try:
        line = None
        while True:
            ran = True
            try:
                ran = jep.eval(line)
            except Exception as err:
                printedErr = False
                try:
                    if len(err.args):
                        if 'printStackTrace' in dir(err.args[0]):
                            err.args[0].printStackTrace()
                            printedErr = True
                except Exception as exc:
                    print("Error printing stacktrace:", str(exc))
                finally:
                    if not printedErr:
                        print(str(err))

            try:
                if ran:
                    line = raw_input(PS1)
                else:
                    line = raw_input(PS2)
            except:
                break

    finally:
        if has_readline:
            try:
                readline.write_history_file(history_file)
            except IOError as err:
                pass
Example #19
0
def save_history(historyPath=historyPath, endMarkerStr=endMarkerStr):
    import readline
    readline.write_history_file(historyPath)
    # Now filter out those line containing the saveMacro
    lines= filter(lambda lineP, endMarkerStr=endMarkerStr:
                      not lineP.strip().endswith(endMarkerStr), open(historyPath).readlines())
    open(historyPath, 'w+').write(''.join(lines))
Example #20
0
def prompt(jep):
    try:
        line = None
        while True:
            ran = True
            try:
                ran = jep.eval(line)
            except Exception as err:
                # if a user uses exit(), don't print the error
                if 'exceptions.SystemExit' not in str(err.message):
                    traceback.print_exc()

            try:
                if ran:
                    line = raw_input(PS1)
                else:
                    line = raw_input(PS2)
            except:
                break

    finally:
        if has_readline:
            try:
                readline.write_history_file(history_file)
            except IOError:
                pass
Example #21
0
 def savehist():
     try:
         global histfile
         import readline
         readline.write_history_file(histfile)
     except:
         print('Unable to save Python command history')
Example #22
0
def getInput(prompt, default=None, options=None, password=False):
	'''
	'''
	readline.write_history_file(historyFile)
	readline.clear_history()
	try:
		width = 45
		suggestion = ''
		if default:
			suggestion = '[{:s}]'.format(default)
			width-= len(suggestion)
		elif options:
			suggestion = '{' + '|'.join(options) + '}'
			width-= len(suggestion)
		formatString = '''{:<''' + str(width) + '''s}{:s}: '''
		fullPrompt = formatString.format(prompt, suggestion)
		userInput = (raw_input(fullPrompt).lower().strip() if not password
			     else getpass(fullPrompt))
		readline.clear_history()
		while (options) and (userInput not in options):
			putMessage("Invalid option!",level = severity.ERROR)
			userInput = (raw_input(fullPrompt).lower().strip() if not password
				     else getpass(fullPrompt))
			
			readline.clear_history()
		readline.read_history_file(historyFile)
		userInput = userInput if userInput else None
		return userInput
	except KeyboardInterrupt:
		readline.read_history_file(historyFile)
		raise
 def postloop(self):
     self._msgbody_save([])
     try:
         readline.write_history_file(HISTORY_FILE)
     except IOError, e:
         # Assume can't write and forget about it
         pass
Example #24
0
 def _cli_loop(self):
     '''
     Starts the configuration shell interactive loop, that:
         - Goes to the last current path
         - Displays the prompt
         - Waits for user input
         - Runs user command
     '''
     while not self._exit:
         try:
             readline.parse_and_bind("%s: complete" % self.complete_key)
             readline.set_completer(self._complete)
             cmdline = raw_input(self._get_prompt()).strip()
         except EOFError:
             self.con.raw_write('exit\n')
             cmdline = "exit"
         self.run_cmdline(cmdline)
         if self._save_history:
             try:
                 readline.write_history_file(self._cmd_history)
             except IOError:
                 self.log.warning(
                     "Cannot write to command history file %s." \
                     % self._cmd_history)
                 self.log.warning(
                     "Saving command history has been disabled!")
                 self._save_history = False
Example #25
0
def save_history(historyPath=historyPath):
    import readline
    try:
        readline.set_history_length(1000)
        readline.write_history_file(historyPath)
    except IOError:
        print 'skipping the history writing'
Example #26
0
 def save_history(new_historyPath=historyPath):
     try:
         import readline
     except ImportError:
         print("Import Error in __main__: Module readline not available.")
     else:
         readline.write_history_file(new_historyPath)
Example #27
0
def start(**kwargs):
    shell = Civ4Shell(**kwargs)
    # completer = Completer(shell=shell)

    # Load history
    try:
        readline.read_history_file(PYCONSOLE_HIST_FILE)
    except IOError:
        shell.warn("Can't read history file")

    # Load help system in background thread
    # doc_thread = Thread(target=load_civ4_library)
    # doc_thread.start()

    # Start Input loop
    try:
        shell.cmdloop()
    except KeyboardInterrupt:
        shell.warn("Ctrl+C pressed. Quitting Civ4 shell.")
        shell.close()
    except TypeError:
        shell.warn("Type error. Quitting Civ4 shell.")
        shell.close()
    finally:
        shell.close()

    # Write history
    try:
        readline.set_history_length(100000)
        readline.write_history_file(".pyconsole.history")
    except IOError:
        shell.warn("Can't write history file")
def main():
	parser = argparse.ArgumentParser(description='King Phisher Interactive Database Console', conflict_handler='resolve')
	utilities.argp_add_args(parser)
	config_group = parser.add_mutually_exclusive_group(required=True)
	config_group.add_argument('-c', '--config', dest='server_config', help='the server configuration file')
	config_group.add_argument('-u', '--url', dest='database_url', help='the database connection url')
	arguments = parser.parse_args()

	if arguments.database_url:
		database_connection_url = arguments.database_url
	elif arguments.server_config:
		server_config = configuration.ex_load_config(arguments.server_config)
		database_connection_url = server_config.get('server.database')
	else:
		raise RuntimeError('no database connection was specified')

	engine = manager.init_database(database_connection_url)
	session = manager.Session()
	rpc_session = aaa.AuthenticatedSession(user=getpass.getuser())
	console = code.InteractiveConsole(dict(
		engine=engine,
		graphql_query=graphql_query,
		manager=manager,
		models=models,
		pprint=pprint.pprint,
		rpc_session=rpc_session,
		session=session
	))
	console.interact('starting interactive database console')

	if os.path.isdir(os.path.dirname(history_file)):
		readline.write_history_file(history_file)
Example #29
0
def repl(prompt='emlisp> ', env=None, inport=None, out=sys.stdout):
    if os.path.exists(os.path.expandvars(HISTORY_FILENAME)):
        readline.read_history_file(os.path.expandvars(HISTORY_FILENAME))

    # if env is None:
    #     env = environment.standard_environment()

    if inport is None:
        inport = types.InPort(None, prompt=prompt)

    while True:
        try:
            val = None

            x = read(inport)
            if x is types.eof_object:
                if out:
                    print >> out, '\n'
                readline.write_history_file(os.path.expandvars(
                    HISTORY_FILENAME))
                return

            val = types.eval(x, env)

            if val is not types.nil_object and out:
                print >> out, val.display()

        except Exception as e:
            print '%s: %s' % (type(e).__name__, e)
            if '*debug*' in env:
                traceback.print_exc()
Example #30
0
File: cli.py Project: da4089/monjon
    def exit(self):
        """CLI command to exit the debugger."""

        if os.path.isdir(self.confdir):
            readline.write_history_file(self.histfile)

        sys.exit(0)
Example #31
0
 def save_history(self, histfile):
     readline.write_history_file(histfile)
Example #32
0
 def save_history(history_path=history_path):
     readline.write_history_file(history_path)
Example #33
0
 def save():
     try:
         readline.write_history_file(options.history_file)
     except IOError:
         pass
Example #34
0
 def save_history(historyPath=historyPath):
     import readline
     readline.write_history_file(historyPath)
     if os.path.exists(historyPath):
         readline.read_history_file(historyPath)
Example #35
0
 def precmd(self, line):
     """Saves command history to disk."""
     if readline:
         readline.set_history_length(self.HISTORY_LENGTH)
         readline.write_history_file(self.HISTORY_FILE_PATH)
     return line
Example #36
0
 def postloop(self):
     """ runs when the cmd loop finishes """
     readline.set_history_length(self._histfile_size)
     readline.write_history_file(self._histfile)
Example #37
0
def savehist():
    readline.write_history_file(HISTFILE)
Example #38
0
File: psh.py Project: ergoz/gist
def save_history(path) :
    '''
    Save the current sessions history into the history file
    '''
    print "\nsaving history to ", history_file
    readline.write_history_file(path)
Example #39
0
                raise err
            print ''
            print 'Quit via keyboard interrupt'
            break
        except EOFError:
            print ''
            break
        except SystemExit:
            # optparse.OptParser prints the usage statement and calls
            # sys.exit when there are any option errors.
            # Printing usage good, SystemExit bad. So catch it and do nothing.
            pass
        except BaseException:
            traceback.print_exc()
    if 'readline' in sys.modules:
        readline.write_history_file(history_file)


def run_once(options, args):
    """Run one command.

    Keyword arguments:
      options: Options instance as built and returned by optparse.
      args: Arguments to GoogleCL, also as returned by optparse.

    """
    global discovery

    # If we haven't gotten the list of discovery APIs yet, and they're asking for
    # a discovery API, figure out their email address and then get a list of
    # APIs.
Example #40
0
 def write_history(self):
     readline.write_history_file(self.history_path)
Example #41
0
def _save_history():
    try:
        readline.write_history_file(os.path.join(CONF_DIR, ".history"))
    except IOError:
        pass
Example #42
0
 def save_history(self, histfile):
     readline.set_history_length(1000)
     readline.write_history_file(histfile)
    def save_history(self, histfile):
        if not _has_readline:
            return

        readline.write_history_file(histfile)
Example #44
0
            server.send("shutdown")
        break

    if cmd in servers.keys():
        serverKey, defaultServer = cmd, cmd
        continue

    elif cmd.split()[0] in servers.keys():
        #serverKey=cmd.split()[0]
        #cmd=cmd[cmd.find(" ")+1:]
        serverKey, cmd = cmd.split(" ", 1)

    elif defaultServer in servers.keys():
        serverKey = defaultServer
    else:
        print "no valid server specified"
        continue

    # send the request to the selected server and print the response
    servers[serverKey].send(cmd)
    for l in servers[serverKey].readline():
        print l

    # has the socket been closed?
    if not servers[serverKey].isOpen():
        del servers[serverKey]
        if defaultServer == serverKey:
            defaultServer = ""

readline.write_history_file(".history")
Example #45
0
 def save_history(history_path=history_path):
     import readline
     readline.write_history_file(history_path)
Example #46
0
File: ertshell.py Project: pgdr/ert
    def _save_history(self):
        if self._history_file is not None:
            if not os.path.exists(os.path.dirname(self._history_file)):
                os.makedirs(os.path.dirname(self._history_file))

            readline.write_history_file(self._history_file)
Example #47
0
 def pause(self):
     """Write the current history to the history file and stop readline."""
     readline.write_history_file(self.historyPath)
     readline.clear_history()
     readline.set_completer()
     self.active = False
Example #48
0
def ttyloop(task, nodeset, timeout, display, remote):
    """Manage the interactive prompt to run command"""
    readline_avail = False
    interactive = task.default("USER_interactive")
    if interactive:
        try:
            import readline
            readline_setup()
            readline_avail = True
        except ImportError:
            pass
        display.vprint(VERB_STD, \
            "Enter 'quit' to leave this interactive mode")

    rc = 0
    ns = NodeSet(nodeset)
    ns_info = True
    cmd = ""
    while task.default("USER_running") or \
            (interactive and cmd.lower() != 'quit'):
        try:
            # Set SIGUSR1 handler if needed
            if task.default("USER_handle_SIGUSR1"):
                signal.signal(signal.SIGUSR1, signal_handler)

            if task.default("USER_interactive") and \
                    not task.default("USER_running"):
                if ns_info:
                    display.vprint(VERB_QUIET, \
                                   "Working with nodes: %s" % ns)
                    ns_info = False
                prompt = "clush> "
            else:
                prompt = ""
            try:
                cmd = raw_input(prompt)
                assert cmd is not None, "Result of raw_input() is None!"
            finally:
                signal.signal(signal.SIGUSR1, signal.SIG_IGN)
        except EOFError:
            print()
            return
        except UpdatePromptException:
            if task.default("USER_interactive"):
                continue
            return
        except KeyboardInterrupt as kbe:
            # Caught SIGINT here (main thread) but the signal will also reach
            # subprocesses (that will most likely kill them)
            if display.gather:
                # Suspend task, so we can safely access its data from here
                task.suspend()

                # If USER_running is not set, the task had time to finish,
                # that could mean all subprocesses have been killed and all
                # handlers have been processed.
                if not task.default("USER_running"):
                    # let's clush_excepthook handle the rest
                    raise kbe

                # If USER_running is set, the task didn't have time to finish
                # its work, so we must print something for the user...
                print_warn = False

                # Display command output, but cannot order buffers by rc
                nodesetify = lambda v: (v[0], NodeSet._fromlist1(v[1]))
                for buf, nodeset in sorted(map(nodesetify,
                                               task.iter_buffers()),
                                           key=bufnodeset_cmpkey):
                    if not print_warn:
                        print_warn = True
                        display.vprint_err(VERB_STD, \
                            "Warning: Caught keyboard interrupt!")
                    display.print_gather(nodeset, buf)

                # Return code handling
                verbexit = VERB_QUIET
                if display.maxrc:
                    verbexit = VERB_STD
                ns_ok = NodeSet()
                for rc, nodelist in task.iter_retcodes():
                    ns_ok.add(NodeSet._fromlist1(nodelist))
                    if rc != 0:
                        # Display return code if not ok ( != 0)
                        nsdisp = ns = NodeSet._fromlist1(nodelist)
                        if display.verbosity >= VERB_QUIET and len(ns) > 1:
                            nsdisp = "%s (%d)" % (ns, len(ns))
                        msgrc = "clush: %s: exited with exit code %d" % (
                            nsdisp, rc)
                        display.vprint_err(verbexit, msgrc)

                # Add uncompleted nodeset to exception object
                kbe.uncompleted_nodes = ns - ns_ok

                # Display nodes that didn't answer within command timeout delay
                if task.num_timeout() > 0:
                    display.vprint_err(verbexit, \
                        "clush: %s: command timeout" % \
                            NodeSet._fromlist1(task.iter_keys_timeout()))
            raise kbe

        if task.default("USER_running"):
            ns_reg, ns_unreg = NodeSet(), NodeSet()
            for client in task._engine.clients():
                if client.registered:
                    ns_reg.add(client.key)
                else:
                    ns_unreg.add(client.key)
            if ns_unreg:
                pending = "\nclush: pending(%d): %s" % (len(ns_unreg),
                                                        ns_unreg)
            else:
                pending = ""
            display.vprint_err(VERB_QUIET,
                               "clush: interrupt (^C to abort task)")
            gws = list(task.gateways)
            if not gws:
                display.vprint_err(
                    VERB_QUIET, "clush: in progress(%d): %s%s" %
                    (len(ns_reg), ns_reg, pending))
            else:
                display.vprint_err(
                    VERB_QUIET, "clush: in progress(%d): %s%s\n"
                    "clush: [tree] open gateways(%d): %s" %
                    (len(ns_reg), ns_reg, pending, len(gws),
                     NodeSet._fromlist1(gws)))
            for gw, (chan, metaworkers) in task.gateways.items():
                act_targets = NodeSet.fromlist(mw.gwtargets[gw]
                                               for mw in metaworkers)
                if act_targets:
                    display.vprint_err(
                        VERB_QUIET, "clush: [tree] in progress(%d) on %s: %s" %
                        (len(act_targets), gw, act_targets))
        else:
            cmdl = cmd.lower()
            try:
                ns_info = True
                if cmdl.startswith('+'):
                    ns.update(cmdl[1:])
                elif cmdl.startswith('-'):
                    ns.difference_update(cmdl[1:])
                elif cmdl.startswith('@'):
                    ns = NodeSet(cmdl[1:])
                elif cmdl == '=':
                    display.gather = not display.gather
                    if display.gather:
                        display.vprint(VERB_STD, \
                            "Switching to gathered output format")
                    else:
                        display.vprint(VERB_STD, \
                            "Switching to standard output format")
                    task.set_default("stdout_msgtree", \
                                     display.gather or display.line_mode)
                    ns_info = False
                    continue
                elif not cmdl.startswith('?'):  # if ?, just print ns_info
                    ns_info = False
            except NodeSetParseError:
                display.vprint_err(VERB_QUIET, \
                    "clush: nodeset parse error (ignoring)")

            if ns_info:
                continue

            if cmdl.startswith('!') and len(cmd.strip()) > 0:
                run_command(task, cmd[1:], None, timeout, display, remote)
            elif cmdl != "quit":
                if not cmd:
                    continue
                if readline_avail:
                    readline.write_history_file(get_history_file())
                run_command(task, cmd, ns, timeout, display, remote)
    return rc
Example #49
0
def _onExit(dirName, hFile):
    # save history only for master process
    if fork_child_pid == 0:
        readline.write_history_file(hFile)
    # remove tmp dir
    commands_get_output('rm -rf %s' % dirName)
Example #50
0
 def set_quit(self):
     """quit hook: save commands in the history file"""
     if readline is not None:
         readline.write_history_file(self._histfile)
     Pdb.set_quit(self)
Example #51
0
 def save_history(path):
     readline.write_history_file(path)
Example #52
0
 def writehistory():
     if self.active:
         readline.write_history_file(self.historyPath)
Example #53
0
 def default(self, line):
     self.result = line
     readline.write_history_file(self.history_file)
     return True
Example #54
0
 def write_history():
     if not has_written[0]:
         readline.write_history_file(history_path)
         print('Written history to %s' % history_path)
         has_written[0] = True
Example #55
0
def save_history(histfile):
    """ Write the history of the user command in a file """
    readline.write_history_file(histfile)
Example #56
0
def _exit_cmd_loop():
    if readline:
        try:
            readline.write_history_file()
        except IOError:
            pass
Example #57
0
 def do_quit(self, args):
     """ESCAPE FROM ESC :D"""
     print "Quitting."
     readline.write_history_file("%s/.esc_history" % os.environ['HOME'])
     raise SystemExit
Example #58
0
 def postloop(self):
     if readline:
         readline.set_history_length(histfile_size)
         readline.write_history_file(histfile)
    def push(self, line):
        # Save the history every time because there seems to be no other way
        # to ensure that history is kept when the session is Ctrl+C'd.
        readline.write_history_file(self.histfile)

        # 'line' is in unicode. Convert line to ascii. Ignore non-ascii characters.
        line = line.encode("ascii", "ignore")
        words = self._split(line)

        if len(words) > 0:
            cmd = words[0]
            if cmd == 'lasterr':
                line = "hc.lasterr()"

            elif cmd == 'ls':
                # Handle ls shortcuts
                arg = '.'
                if len(words) > 1:
                    arg = words[1]
                line = 'os.listdir("' + arg + '")'

            elif cmd == 'pwd':
                line = 'os.getcwd()'

            elif cmd == 'cd':
                if len(words) == 1:
                    line = 'os.getcwd()'
                else:
                    path = " ".join(words[1:]).replace("\\", "/")
                    line = 'os.chdir("' + path + '")'

            # If the line starts with '!', give it to the system shell
            elif line[0] == '!':
                if line[0:3] == '!cd':
                    path = " ".join(words[1:]).replace("\\", "/")
                    line = "os.chdir('" + path + "')"
                else:
                    line = "os.system('" + line[1:] + "')"

            # If it ends in hex, wrap the line in a call of kalaccess.toHex()
            elif line[-3:] == "hex":
                line = line[:-3]
                line = "kalaccess.toHex(" + line + ")"

            elif line[-4:] == "help":
                line = line[:-4]
                line = "help(" + line + ")"

            elif line == "who":
                line = "hc.who()"

            elif line[0:4] == "who ":
                sec = line.split()
                pieces = []
                for s in sec[1:]:
                    if s == "all":
                        pieces.append("showAll=True")
                    else:
                        pieces.append("varType='" + s + "'")
                line = "hc.who(" + ", ".join(pieces) + ")"

            elif line == "whos":
                line = "hc.who(newLine=True)"

            elif line[0:5] == "whos ":
                sec = line.split()
                pieces = ["newLine=True"]
                for s in sec[1:]:
                    if s == "all":
                        pieces.append("showAll=True")
                    else:
                        pieces.append("varType='" + s + "'")
                line = "hc.who(" + ", ".join(pieces) + ")"

            elif line == "exit":
                sys.exit()

        # Give the line to the Python interpreter
        return code.InteractiveConsole.push(self, line)
Example #60
0
while(True):
    temp = AllofCode.copy()
    try : 
        c = input("lion> ")
        while(True) :
            if ';' in c:
                break
            c += input("...    ")
        temp.append(c)
        m = mm.model_from_str('\n'.join(temp))
        code = te.genCode(m.rules[-1])
        exec(code)
        pycode += code
        AllofCode.append(c)
        readline.write_history_file('.lion_history')
    except EOFError :
        print("\r   bye :(")
        save_code(pycode)
        break
    except KeyboardInterrupt:
        print("\ntype exit() or EOF to quit!")
    except FileNotFoundError as e:
        print(f'''The file "{e.args[1].split("'")[1]}" does not exist!''')
    except tx.exceptions.TextXSyntaxError as e:
        print(f'''SyntaxError: name '{e.message.split("'")[-2]}' is not defined''')
    except tx.exceptions.TextXSemanticError as e:
        print(f'''SemanticError: '{e.message}' is not defined''')
    except Exception as e:
        print(e)