def save_history(self): if hasReadline and self._history_path: readline.set_history_length(1000) try: readline.write_history_file(self._history_path) except: pass
def setup(self): """ Initialization of third-party libraries Setting interpreter history. Setting appropriate completer function. :return: """ if not os.path.exists(self.history_file): with open(self.history_file, 'a+') as history: if is_libedit(): history.write("_HiStOrY_V2_\n\n") readline.read_history_file(self.history_file) readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, self.history_file) readline.parse_and_bind('set enable-keypad on') readline.set_completer(self.complete) readline.set_completer_delims(' \t\n;') if is_libedit(): readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete")
def _pythonrc_enable_history(): import atexit import os try: import readline except: return # "NOHIST= python" will disable history if 'NOHIST' not in os.environ: history_path = os.path.expanduser('~/.history/python') has_written = [False] 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 atexit.register(write_history) if os.path.isfile(history_path): try: readline.read_history_file(history_path) except IOError: pass readline.set_history_length(-1)
def history_init(self, filename, size): self.history_file = filename self.history_size = size if filename and os.path.exists(filename): readline.read_history_file(filename) readline.set_history_length(size) self.history_reset()
def __init__(self, *args, **kwargs): self.restshlib = restshlib.RestSHLib(global_data=self.global_data) self.prompt = self.cfg_prompt % {"login": self.login, "baseurl": self.baseurl} readline.read_history_file(self.history_file) readline.set_history_length(self.history_file_max_lines) super(RestSH, self).__init__(*args, **kwargs)
def setup(): # Create temporary directory for storing serialized objects. if not os.path.exists("_temp/"): os.mkdir("_temp/") # Configure log file for the application. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s', filename='cl_gui.log') logging.info("Starting application...") # Code snippet for recalling previous commands with the # 'up' and 'down' arrow keys. import rlcompleter import atexit import readline hist_file = os.path.join(os.environ['HOME'], '.pythonhistory') try: readline.read_history_file(hist_file) except IOError: pass # Set a limit on the number of commands to remember. # High values will hog system memory! readline.set_history_length(25) atexit.register(readline.write_history_file, hist_file) # Tab completion for GUI commands def completer(text, state): commands = Status.ALL_COMMANDS file_paths = [] for dirname, dirnames, filenames in os.walk('.'): if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git') # Add path to subdirectories file_paths.extend([os.path.join(dirname, sub_dir) for sub_dir in dirnames]) # Add path to all filenames in subdirectories. file_paths.extend([os.path.join(dirname, filename) for filename in filenames]) # Remove './' header in file strings. file_paths = [file.strip('./') for file in file_paths] options = [i for i in commands if i.startswith(text)] options.extend([f for f in file_paths if f.startswith(text)]) try: return options[state] except IndexError: return None readline.set_completer(completer) # Bind tab completer to specific platforms if readline.__doc__ and 'libedit' in readline.__doc__: readline.parse_and_bind("bind -e") readline.parse_and_bind("bind '\t' rl_complete") else: readline.parse_and_bind("tab: complete") del hist_file, readline, rlcompleter
def __init__(self, config): self.config = config self._buffer = '' self.no_response = object() self.prompt = '>> ' if HAS_READLINE and config['terms_history_file'] and int(config['terms_history_length']): readline.set_history_length(int(config['terms_history_length'])) fn = os.path.expanduser(config['terms_history_file']) try: if not os.path.exists(fn): with open(fn, 'w') as f: f.write('# terms history\n') readline.read_history_file(fn) except Exception: pass address = '%s/%s' % (config['dbms'], config['dbname']) engine = create_engine(address) Session = sessionmaker(bind=engine) if config['dbname'] == ':memory:': from terms.core.terms import Base Base.metadata.create_all(engine) from terms.core.network import Network Network.initialize(Session()) self.compiler = Compiler(Session(), config) register_exec_global(Runtime(self.compiler), name='runtime')
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
def main(): ''' The main entry point ''' salt_vars = get_salt_vars() def salt_outputter(value): ''' Use Salt's outputters to print values to the shell ''' if value is not None: try: import __builtin__ __builtin__._ = value except ImportError: __builtins__._ = value salt.output.display_output(value, '', salt_vars['__opts__']) sys.displayhook = salt_outputter # Set maximum number of items that will be written to the history file readline.set_history_length(300) if os.path.exists(HISTFILE): readline.read_history_file(HISTFILE) atexit.register(savehist) atexit.register(lambda: sys.stdout.write('Salt you later!\n')) saltrepl = InteractiveConsole(locals=salt_vars) saltrepl.interact(banner=__doc__)
def run(self): print('tiget {}'.format(__version__)) print('Type "help" for help') print('') readline.parse_and_bind('tab: complete') try: readline.read_history_file(self.histfile) except IOError: pass # The file might not exist yet while True: self.lineno += 1 try: line = self.readline() if line in ('quit', 'exit'): raise EOFError(line) except KeyboardInterrupt: continue except EOFError: break try: cmd_exec(line) except CmdError as e: print_error('"<repl>", line {}: {}'.format(self.lineno, e)) except: post_mortem() readline.set_history_length(settings.core.history_limit) readline.write_history_file(self.histfile)
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 save_history(historyPath=historyPath): import readline try: readline.set_history_length(1000) readline.write_history_file(historyPath) except IOError: print 'skipping the history writing'
def Interact(session): import readline try: readline.read_history_file(session.config.history_file()) except IOError: pass readline.set_history_length(100) try: while True: session.ui.block() opt = raw_input('mailpile> ').decode('utf-8').strip() session.ui.unblock() if opt: if ' ' in opt: opt, arg = opt.split(' ', 1) else: arg = '' try: Action(session, opt, arg) except UsageError, e: session.error(str(e)) except EOFError: print readline.write_history_file(session.config.history_file())
def __init__(self, inp=None, out=None, opts={}): get_option = lambda key: Mmisc.option_set(opts, key, DEFAULT_USER_SETTINGS) Minput = import_relative('input', '..inout', 'trepan') Moutput = import_relative('output', '..inout', 'trepan') atexit.register(self.finalize) self.interactive = True # Or at least so we think initially self.input = inp or Minput.DebuggerUserInput() self.output = out or Moutput.DebuggerUserOutput() if self.input.use_history(): complete = get_option('complete') if complete: parse_and_bind("tab: complete") set_completer(complete) pass self.histfile = get_option('histfile') if self.histfile: try: read_history_file(histfile) except IOError: pass set_history_length(50) atexit.register(write_history_file, self.histfile) pass return
def _reset_readline(): if readline: readline.parse_and_bind("tab: complete") readline.parse_and_bind("set horizontal-scroll-mode on") readline.parse_and_bind("set page-completions on") readline.set_completer_delims(" ") readline.set_history_length(500)
def __init__(self): super().__init__() try: import readline readline.set_history_length(core.MAX_HISTORY_SIZE) except ImportError: pass
def __setup(): import os import atexit import sys import pprint import readline import rlcompleter import platform HISTORYFILE = os.path.join(os.environ['HOME'], '.python-history') if platform.system() == 'Darwin': readline.parse_and_bind("bind ^I rl_complete") # mac (bsd libedit) else: readline.parse_and_bind("tab: complete") # gnu readline try: readline.read_history_file(HISTORYFILE) except IOError: pass # It doesn't exist yet. readline.set_history_length(100) atexit.register(lambda: readline.write_history_file(HISTORYFILE)) sys.ps1 = '\n\x1b[0;32m \x1b[1;32m>>\x1b[0;32m \x1b[0m: ' sys.ps2 = ' ... ' _pprinter = pprint.PrettyPrinter(indent=4).pprint def pprinter(value): __builtins__._ = value # populate _ with result of previous statement sys.stdout.write('\x1b[0;31m \x1b[1;31m<<\x1b[0;31m \x1b[0m: ') _pprinter(value) sys.displayhook = pprinter
def __init__(self, options): """ Constructor """ readline.parse_and_bind("tab: complete") readline.set_completer(self.complete) readline.set_completion_display_matches_hook(self.completer_print) try: readline.read_history_file(CLI_HISTORY) except IOError: pass readline.set_history_length(CLI_MAX_CMD_HISTORY) if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER): os.system('rm -rf %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER)) os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER)) try: self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True) except: os.system('rm -rf %s' % CLI_RESULT_HISTORY_KEY) self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True) print "\nRead history file: %s error. Has recreate it.\n" % CLI_RESULT_HISTORY_KEY self.start_key = 'start_key' self.last_key = 'last_key' self.cli_cmd_func = {'help': self.show_help, 'history': self.show_help, 'more': self.show_more, 'quit': sys.exit, 'exit': sys.exit, 'save': self.save_json_to_file} self.cli_cmd = self.cli_cmd_func.keys() self.raw_words_db = self._parse_api_name(inventory.api_names) self.words_db = list(self.raw_words_db) self.words_db.extend(self.cli_cmd) self.words = list(self.words_db) self.is_cmd = False self.curr_pattern = None self.matching_words = None self.api_class_params = {} self.build_api_parameters() self.api = None self.account_name = None self.user_name = None self.session_uuid = None if os.path.exists(SESSION_FILE): try: with open(SESSION_FILE, 'r') as session_file_reader: self.session_uuid = session_file_reader.readline().rstrip() self.account_name = session_file_reader.readline().rstrip() self.user_name = session_file_reader.readline().rstrip() except EOFError: pass self.hostname = options.host self.port = options.port self.no_secure = options.no_secure self.api = api.Api(host=self.hostname, port=self.port)
def main(): """Main function.""" # Enable tab completion readline.parse_and_bind('tab: complete') # Set prompt sys.ps1 = colorize_prompt('>>> ', 'blue', 'bold') sys.ps2 = colorize_prompt('... ', 'yellow', 'bold') # Constrict history size readline.set_history_length(HISTSIZE) # Create custom history file touch(CUSTOM_HISTFILE) # Load custom history file load_history(CUSTOM_HISTFILE) # Use custom history file atexit.register(readline.write_history_file, CUSTOM_HISTFILE) # Remove default history at exit atexit.register(remove_file, DEFAULT_HISTFILE) # Use pprint to print variables sys.displayhook = displayhook_pprint
def _init_history(self): try: readline.set_history_length(100) readline.read_history_file(self._history_file) except IOError: pass atexit.register(self._save_history)
def pythonrc_enable_history(): import os import sys try: import readline except ImportError as e: sys.stderr.write(str(e) + " - Command-line history is disabled.\n") else: # The history file. PYHISTORY = os.path.expanduser('~/.pyhistory') # Restore command-line history. if os.path.isfile(PYHISTORY): readline.read_history_file(PYHISTORY) # Save command-line history when Python exits. try: import atexit except ImportError as e: sys.stderr.write(str(e) + " - Command-line history will not be saved when Python exits.\n") else: atexit.register(readline.write_history_file, PYHISTORY) # Set history size. readline.set_history_length(10000000)
def init_history(self, histfile): if hasattr(readline, "read_history_file"): tryBackup = False try: tryBackup = not os.path.exists(histfile) if not tryBackup: historyFileDesc = open(histfile) historyFileDesc.seek(0, 2) tryBackup = (historyFileDesc.tell() == 0) historyFileDesc.close() except: tryBackup = False try: if tryBackup: try: if os.path.exists(histfile + '_backup'): import shutil shutil.copy(histfile + '_backup', histfile) except: pass readline.read_history_file(histfile) except IOError: pass readline.set_history_length(1000) atexit.register(self.save_history, histfile)
def __init__(self, env): self.__ps1 = "ZAS[%(cmdno)s/%(lineno)s]> " self.__ps2 = "ZAS[%(cmdno)s/%(lineno)s]: " self.__cmdno = 1 self.__lineno = 1 self.env = env readline.set_history_length(1000)
def __init__( self ): cmd.Cmd.__init__( self ) self.connected = False self.masterURL = "unset" self.writeEnabled = False self.modifiedData = False self.rpcClient = None self.do_connect() if self.connected: self.modificator = Modificator ( self.rpcClient ) else: self.modificator = Modificator() self.identSpace = 20 self.backupFilename = "dataChanges" self._initSignals() #User friendly hack self.do_exit = self.do_quit # store history histfilename = os.path.basename(sys.argv[0]) historyFile = os.path.expanduser( "~/.dirac/%s.history" % histfilename[0:-3]) if not os.path.exists( os.path.dirname(historyFile) ): os.makedirs( os.path.dirname(historyFile) ) if os.path.isfile( historyFile ): readline.read_history_file( historyFile ) readline.set_history_length(1000) atexit.register( readline.write_history_file, historyFile )
def Interact(session): import readline try: readline.read_history_file(session.config.history_file()) except IOError: pass # Negative history means no saving state to disk. history_length = session.config.sys.history_length if history_length >= 0: readline.set_history_length(history_length) else: readline.set_history_length(-history_length) try: prompt = session.ui.palette.color('mailpile> ', color=session.ui.palette.BLACK, weight=session.ui.palette.BOLD) while True: session.ui.block() opt = raw_input(prompt).decode('utf-8').strip() session.ui.unblock() if opt: if ' ' in opt: opt, arg = opt.split(' ', 1) else: arg = '' try: session.ui.display_result(Action(session, opt, arg)) except UsageError, e: session.error(unicode(e)) except UrlRedirectException, e: session.error('Tried to redirect to: %s' % e.url)
def __init__(self, base, conf=None, path=None, task=None, wait=None): cmd.Cmd.__init__(self) self.base = urlparse.urlparse(base) self.user = getpass.getuser() self.hdfs = WebHDFSClient(self.base._replace(path='').geturl(), self.user, conf, wait) self.do_cd(path or self.base.path) if task: self.onecmd(' '.join(task)) sys.exit(0) try: self.hist = os.path.join(os.path.expanduser('~'), os.environ.get('WEBHDFS_HISTFILE', '.webhdfs_history')) readline.read_history_file(self.hist) except IOError: pass try: readline.set_history_length(int(os.environ.get('WEBHDFS_HISTSIZE', 3))) except ValueError: readline.set_history_length(0) if os.access(self.hist, os.W_OK): atexit.register(readline.write_history_file, self.hist)
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)
def save_histfile(self): # Only write to file if not in crypto mode if not self.session.config.crypt_session: # Write the command to the history file if self.session.config.histsize != 0: readline.set_history_length(self.session.config.histsize) readline.write_history_file('cmdhistory')
def cmdloop(self, intro=None): self.preloop() if self.use_rawinput and self.completekey: try: readline.read_history_file(self.conf['history_file']) readline.set_history_length(self.conf['history_size']) except IOError: # if history file does not exist try: open(self.conf['history_file'], 'w').close() readline.read_history_file(self.conf['history_file']) except IOError: pass self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") try: if intro is not None: self.intro = intro if self.conf['intro']: self.stdout.write(str(self.conf['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: self.stdout.write('\n') line = '' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] # chop \n line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: readline.set_completer(self.old_completer) except ImportError: pass try: readline.write_history_file(self.conf['history_file']) except IOError: self.log.error('WARN: couldn\'t write history ' \ 'to file %s\n' % self.conf['history_file'])
def __init__(self): super().__init__() try: import readline readline.set_history_length(core.MAX_HISTORY_SIZE) readline.set_completer_delims(READLINE_COMPLETER_DELIMS) except ImportError: pass
def setup_readline(): """Sets up the readline module and completion supression, if available.""" global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE if RL_COMPLETION_SUPPRESS_APPEND is not None: return try: import readline except ImportError: return import ctypes import ctypes.util readline.set_completer_delims(' \t\n') if not readline.__file__.endswith('.py'): RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__) try: RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll( lib, 'rl_completion_suppress_append') except ValueError: # not all versions of readline have this symbol, ie Macs sometimes RL_COMPLETION_SUPPRESS_APPEND = None RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size') # reads in history env = builtins.__xonsh_env__ hf = env.get('XONSH_HISTORY_FILE', os.path.expanduser('~/.xonsh_history')) if os.path.isfile(hf): try: readline.read_history_file(hf) except PermissionError: warn('do not have read permissions for ' + hf, RuntimeWarning) hs = env.get('XONSH_HISTORY_SIZE', 8128) readline.set_history_length(hs) # sets up IPython-like history matching with up and down readline.parse_and_bind('"\e[B": history-search-forward') readline.parse_and_bind('"\e[A": history-search-backward') # Setup Shift-Tab to indent readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT', ''))) # handle tab completion differences found in libedit readline compatibility # as discussed at http://stackoverflow.com/a/7116997 if readline.__doc__ and 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete")
def main(): repl_env = Env(None) for k, v in core.ns.items(): repl_env.set(k, v) repl_env.set('eval', lambda ast: mal_eval(ast, repl_env)) readline.set_history_length(1000) for s in core.builtins: mal_eval(reader.read_str(s), repl_env) while True: try: rep(repl_env) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as e: print(f"Error: {e}")
def do_quit(self, args, force=True, status=0): """Quits the program.""" self.oprint("Quitting.") if 'force' in str(args).lower(): force = True if not force: if 'saveall' in str(args).lower(): self.env.save_all() else: diff = self.env.get_config_diff() if diff: self.eprint("Configuration has not been saved.\n" "Save now or use 'quit force' to quit" " without saving,\n" "or 'quit saveall' to save upon quit") return try: if hasattr(self.env, 'logger'): for handler in self.env.logger.handlers: handler.close() except: pass try: import readline history_path = getattr(self.env.simplecli_config, 'history_file', None) if history_path: if not os.path.exists(history_path): open(history_path, 'w').close() readline.set_history_length(100) readline.write_history_file(history_path) except ImportError: pass except: self.eprint('Error setting readline history on quit') print_exc() raise try: if self._old_completer: readline.set_completer(self._old_completer) except: pass raise SystemExit
def repl_readline_helper(env): try: import readline, atexit, rlcompleter except ImportError: print("readline module is not installed! use raw input") readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode vi') readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>?') completer = rlcompleter.Completer(env, readline) readline.set_completer(completer.complete) #readline.set_completer(completer.pathCompleter) histfile = os.path.join(PSH_DIR, ".pyhist") try: readline.read_history_file(histfile) # default history len is -1 (infinite), which may grow unruly readline.set_history_length(1000) except IOError: pass atexit.register(readline.write_history_file, histfile)
def init_readline(self): """Activates history and tab completion """ # - init history if os.path.exists(config['HISTFILE']): readline.read_history_file(config['HISTFILE']) readline.set_history_length(config['HISTSIZE']) atexit.register(partial(readline.write_history_file, config['HISTFILE'])) # - turn on tab completion readline.parse_and_bind('tab: complete') readline.set_completer(self.improved_rlcompleter()) # - enable auto-indenting readline.set_pre_input_hook(self.auto_indent_hook) # - other useful stuff readline.read_init_file()
def setup_readline(): """Sets up the readline module and completion suppression, if available.""" global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE, RL_STATE, readline if RL_COMPLETION_SUPPRESS_APPEND is not None: return try: import readline except ImportError: return import ctypes import ctypes.util readline.set_completer_delims(' \t\n') if not readline.__file__.endswith('.py'): RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__) try: RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll( lib, 'rl_completion_suppress_append') except ValueError: # not all versions of readline have this symbol, ie Macs sometimes RL_COMPLETION_SUPPRESS_APPEND = None try: RL_STATE = ctypes.c_int.in_dll(lib, 'rl_readline_state') except: pass RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size') env = builtins.__xonsh_env__ # reads in history readline.set_history_length(-1) ReadlineHistoryAdder() # sets up IPython-like history matching with up and down readline.parse_and_bind('"\e[B": history-search-forward') readline.parse_and_bind('"\e[A": history-search-backward') # Setup Shift-Tab to indent readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT'))) # handle tab completion differences found in libedit readline compatibility # as discussed at http://stackoverflow.com/a/7116997 if readline.__doc__ and 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # load custom user settings readline.read_init_file()
def pre_input(self, completefn): if self.raw_input: if HAVE_READLINE: import atexit self.old_completer = readline.get_completer() # Fix Bug #3129: Limit the history size to consume less memory readline.set_history_length(self.historysize) readline.set_completer(completefn) readline.parse_and_bind(self.completekey + ": complete") try: readline.read_history_file() except IOError: pass atexit.register(readline.write_history_file) self.havecolor = True if mswindows and self.enablecolor: self.cwrite = readline.GetOutputFile().write_color else: self.cwrite = self.stdout.write
def __init__(self, ctx, cli): self.ctx = ctx self.cli = cli self.exit_cmds = ['quit', 'exit'] code.InteractiveConsole.__init__(self) history_file = os.path.join(ctx.obj.home_dir, self.HISTORY_FILE) try: readline.read_history_file(history_file) except IOError: pass readline.set_history_length(self.HISTORY_LEN) readline.set_completer(self.complete) if 'libedit' in readline.__doc__: # sigh, apple readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") atexit.register(readline.write_history_file, history_file)
def run_prompt(): import readline lox_history_filename = '.lox_history' lox_history_file = Path('.lox_history') if not lox_history_file.is_file(): open(lox_history_file, 'w').close() readline.read_history_file('.lox_history') try: while True: print('> ', end='') lox_interpreter.run(input()) lox_interpreter.had_error = False except (EOFError, KeyboardInterrupt) as e: print(f'\nShutting Down.\nReason: {repr(e)}') finally: readline.set_history_length(1000) readline.write_history_file('.lox_history')
def main(args): histfile = os.path.join(os.path.expanduser("~"), ".red_history") try: readline.read_history_file(histfile) readline.set_history_length(1000) except IOError: pass atexit.register(readline.write_history_file, histfile) del histfile command_line = [] breakpoints = [] for arg in args: if arg.startswith('@'): breakpoints.append(arg[1:]) else: command_line.append(arg) if len(command_line) == 0: print('Usage: red /path/to/your/target.byte') return 1 dbgr = subprocess.Popen(['ocamldebug', '-emacs'] + command_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print( debugger_command(dbgr, '')[0].replace( '\tOCaml Debugger version ', vt100.red(u'\u2022 RED') + ' OCamlDebug v')) print(vt100.dim('Press ? for help')) print(debugger_command(dbgr, 'start')[0]) auto_run = True for bp in breakpoints: if bp == '': auto_run = False else: print(debugger_command(dbgr, 'break @ ' + bp.replace(':', ' '))[0]) console = vt100.Console() return repl(dbgr, console, auto_run)
def _pythonrc_enable_readline(): """Enable readline, tab completion, and history""" import sys try: import readline import rlcompleter except ImportError: sys.stderr.write('readline unavailable - tab completion disabled.\n') return old_complete = readline.get_completer() def complete(text, state): if not text: # Insert four spaces for indentation return (' ', None)[state] else: return old_complete(text, state) readline.parse_and_bind('tab: complete') readline.set_completer(complete) import atexit import os # "NOHIST= python" will disable history if 'NOHIST' not in os.environ: history_path = os.path.expanduser('~/.pyhistory') has_written = [False] def write_history(): if not has_written[0]: readline.write_history_file(history_path) has_written[0] = True atexit.register(write_history) if os.path.isfile(history_path): readline.read_history_file(history_path) readline.set_history_length(10000000)
def repl(local, histfile=None, banner=None): import readline import rlcompleter if 'libedit' in readline.__doc__: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') if histfile is not None and os.path.exists(histfile): # avoid duplicate reading if readline.get_current_history_length() <= 0: readline.set_history_length(10000) readline.read_history_file(histfile) import code readline.set_completer(rlcompleter.Completer(local).complete) if sys.version_info >= (3, 6): code.interact(local=local, banner=banner, exitmsg='') else: code.interact(local=local, banner=banner) if histfile is not None: readline.write_history_file(histfile)
def get_input(prompt=''): """ Get input that is Py2/Py3 compatible and keep the input in a history file. """ histfile = os.path.join(os.path.expanduser("~"), ".runnerhistory") try: readline.set_history_length(1000) readline.read_history_file(histfile) line = raw_input(prompt) readline.write_history_file(histfile) except NameError: readline.set_history_length(1000) readline.read_history_file(histfile) line = input(prompt) readline.write_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) return line
def main(): if os.name == 'posix': readline.set_history_length(1000) parser = argparse.ArgumentParser(prog='libra-shell') parser.add_argument('-a', "--host", default="ac.testnet.libra.org", help='Host address/name to connect to') parser.add_argument( '-p', "--port", default=8000, help='Admission Control port to connect to. [default: 8000]') parser.add_argument( '-r', "--sync", default=False, help='If set, client will sync with validator during wallet recovery.') libra_args = parser.parse_args(sys.argv[1:]) run_shell(libra_args)
def setup(self): """ Initialization of third-party libraries Setting interpreter history. Setting appropriate completer function. :return: """ if not os.path.exists(self.history_file): open(self.history_file, 'a+').close() readline.read_history_file(self.history_file) readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, self.history_file) readline.parse_and_bind('set enable-keypad on') readline.set_completer(self.complete) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete")
def pdb_init(): # return to debugger after fatal exception (Python cookbook 14.5): def return_to_debugger(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): sys.__excepthook__(type, value, tb) import traceback, pdb traceback.print_exception(type, value, tb) print pdb.pm() sys.excepthook = return_to_debugger histfile = ".pdb_history" import readline try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) readline.set_history_length(200)
def __init__(self, client): self.client = client self.options = None histfile = os.path.join(os.path.expanduser("~/.local/serverboards/"), "cmd_history") try: os.makedirs(os.path.dirname(histfile)) except FileExistsError: pass try: readline.read_history_file(histfile) readline.set_history_length(1000) except FileNotFoundError: pass atexit.register(readline.write_history_file, histfile) readline.set_completer(self.complete) readline.parse_and_bind("tab: complete") readline.set_completer_delims(" \t:\"'")
def _setup_readline(cfg=None, logger=None, *args, **kwargs): if not cfg: return False # Setup tab completion readline.parse_and_bind('tab: complete') readline.set_completer_delims(' \t\n;') completer = Completer(logger=logger) readline.set_completer(completer.complete) # Setup command-line history max_history_length = cfg.get('interactive', 'max_history_length') readline.set_history_length(int(max_history_length, 0)) history_filename = cfg.get('interactive', 'history_file') if os.path.exists(history_filename): readline.read_history_file(history_filename) # Register shutdown function atexit.register(_teardown_readline, history_filename) return True
def Interact(session): import readline try: readline.read_history_file(session.config.history_file()) except IOError: pass # Negative history means no saving state to disk. history_length = session.config.get('history_length', 100) if history_length >= 0: readline.set_history_length(history_length) else: readline.set_history_length(-history_length) try: prompt = session.ui.palette.color('mailpile> ', color=session.ui.palette.BLACK, weight=session.ui.palette.BOLD) while True: session.ui.block() opt = raw_input(prompt).decode('utf-8').strip() session.ui.unblock() if opt: if ' ' in opt: opt, arg = opt.split(' ', 1) else: arg = '' try: session.ui.display_result(Action(session, opt, arg)) except UsageError, e: session.error(unicode(e)) except EOFError: print try: if session.config.get('history_length', 100) > 0: readline.write_history_file(session.config.history_file()) else: os.remove(session.config.history_file()) except OSError: pass
def __init__(self, grammar_or_parser, application='cly', prompt=None, user_context=None, with_context=None, history_file=None, history_length=500, completion_key='tab', completion_delimiters=' \t', help_key='?', inhibit_exceptions=False, with_backtrace=False): if prompt is None: prompt = application + '> ' if history_file is None: history_file = os.path.expanduser('~/.%s_history' % application) if isinstance(grammar_or_parser, Grammar): parser = Parser(grammar_or_parser) else: parser = grammar_or_parser if with_context is not None: parser.with_context = with_context if user_context is not None: parser.user_context = user_context Interact._parser = parser Interact.prompt = prompt Interact.application = application Interact.user_context = user_context Interact.history_file = history_file Interact.history_length = history_length Interact.completion_delimiters = completion_delimiters Interact.completion_key = completion_key try: readline.set_history_length(history_length) readline.read_history_file(history_file) except: pass readline.parse_and_bind("%s: complete" % completion_key) readline.set_completer_delims(self.completion_delimiters) readline.set_completer(Interact._cli_completion) readline.set_startup_hook(Interact._cli_injector) # Use custom readline extensions cly.rlext.bind_key(ord(help_key), Interact._cli_help)
def __init__(self, *args, **kwargs): # the \x01/\x02 are to make the prompt behave properly with the readline library self.prompt = 'pappy\x01' + Colors.YELLOW + '\x02> \x01' + Colors.ENDC + '\x02' self.debug = True self.session = kwargs['session'] del kwargs['session'] self._cmds = {} self._aliases = {} # Only read and save history when not in crypto mode if not self.session.config.crypt_session: atexit.register(self.save_histfile) readline.set_history_length(self.session.config.histsize) if os.path.exists('cmdhistory'): if self.session.config.histsize != 0: readline.read_history_file('cmdhistory') else: os.remove('cmdhistory') cmd2.Cmd.__init__(self, *args, **kwargs)
def _init_completion(self): self.historyfile = self._historyfile() self.matching_words = [ ':%s' % m for m in self.modhandler.modules_classes.keys() ] + [ core.terminal.help_string, core.terminal.load_string, core.terminal.set_string ] try: readline.set_history_length(100) readline.set_completer_delims(' \t\n;') readline.parse_and_bind('tab: complete') readline.set_completer(self._complete) readline.read_history_file(self.historyfile) except IOError: pass atexit.register(readline.write_history_file, self.historyfile)
def __init__(self, options): options.injections = 0 options.latent_iterations = 0 options.compare_all = False options.extract_blocks = False if options.power_switch_outlet is not None: switch = power_switch(options) else: switch = None self.drseus = fault_injector(options, switch) if self.drseus.db.campaign.simics: self.launch_simics() else: self.drseus.debugger.reset_dut() self.prompt = 'DrSEUs> ' Cmd.__init__(self) if exists('.supervisor_history'): read_history_file('.supervisor_history') set_history_length(options.history_length) if self.drseus.db.campaign.aux: self.__class__ = aux_supervisor
def __init__(self, host=None): cmd.Cmd.__init__(self) # Check if Port is given self.host = None self.port = None self.prompt = '[%s]> ' % colorize("no host", "yellow") if host: self.__setHost(host) self.cwd = '' self.previous_cwd = '' self.homeDir = '' # store history histfilename = os.path.basename(sys.argv[0]) historyFile = os.path.expanduser("~/.dirac/%s.history" % histfilename[0:-3]) if not os.path.exists(os.path.dirname(historyFile)): os.makedirs(os.path.dirname(historyFile)) if os.path.isfile(historyFile): readline.read_history_file(historyFile) readline.set_history_length(1000) atexit.register(readline.write_history_file, historyFile)
def __setup(self): """ Setting interpreter history. Setting appropriate completer function. """ if not os.path.exists(self.history_file): open(self.history_file, 'a+').close() readline.read_history_file(self.history_file) readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, self.history_file) readline.parse_and_bind('set enable-keypad on') # TODO find out how to get this list from the grammar words = "open", "save", "list", "info", "history", "layer", "print" completer = Completer(words) readline.set_completer(completer.complete) # readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete")
def __init__(self, options, conf_dir, config_parser): self.session = '' self.current_user = '' self.server = '' self.ssm = {} self.config = {} self.postcmd(False, '') # make the options available everywhere self.options = options # make the configuration file available everywhere self.config_parser = config_parser # this is used when loading and saving caches self.conf_dir = conf_dir self.history_file = os.path.join(self.conf_dir, 'history') try: # don't split on hyphens or colons during tab completion newdelims = readline.get_completer_delims() newdelims = re.sub(':|-|/', '', newdelims) readline.set_completer_delims(newdelims) if not options.nohistory: try: if os.path.isfile(self.history_file): readline.read_history_file(self.history_file) readline.set_history_length(self.HISTORY_LENGTH) # always write the history file on exit atexit.register(readline.write_history_file, self.history_file) except IOError: logging.error('Could not read history file') except: pass
def run(*varargs): histfile = ".client_shell_history" try: readline.read_history_file(histfile) # default history len is -1 (infinite), which may grow unruly readline.set_history_length(1000) except FileNotFoundError: pass atexit.register(readline.write_history_file, histfile) context = Context() context.parser = setup_parser() running = True if len(varargs) > 0: client_id = varargs[0] context.setup_handler(Namespace(client_id=client_id)) while running: try: cmd = input("> ") readline.add_history(cmd) argv = shlex.split(cmd) args = context.parser.parse_args(argv) if args.command in HANDLERS: handler = HANDLERS[args.command] handler(context, args) except KeyboardInterrupt: print("Keyboard Interrupt") exit(0) except EOFError: print("Done") exit(0) except ParserError as ex: print("Error:", ex.args[0]) context.parser.print_usage() except Exception as ex: print("Exception ({}): {}".format(type(ex), ex.args))
def __init__(self, fmdb, locals=None, filename="<console>", \ histfile=os.path.join(os.path.expanduser('~'), '.config', \ 'fmcli-history')): # In Python 2.x this didn't inherit from object, so we're # stuck with the old superclass syntax for now. # super(fmcli, self).__init__(locals, filename) code.InteractiveConsole.__init__(self, locals, filename) self.init_history(histfile) self.fmdb = fmdb readline.set_history_length(1000) self.commands = { ('cache', 'a'): self.do_cache_overview, ('clear_calculated', 'cc'): self.do_clear_calculated, ('calc_inode_stats', 'cs'): self.do_calc_inode_stats, ('help', 'h', '?'): self.do_help, ('ls', ): self.do_ls, ('machine', 'm'): self.do_machine, ('quit', 'exit', 'q'): self.do_exit, ('summary', 's'): self.do_summary, ('units', 'u'): self.do_set_units, ('overview', 'o'): self.do_overview, ('overview_cell', 'oc'): self.do_cell_to_extents, ('overview_types', 'ot'): self.do_overview_extent_types, ('extent_flag', 'ef'): self.do_extent_flag, ('extent_inode', 'ei'): self.do_inodes, ('extent_logical', 'el'): self.do_loff_to_extents, ('extent_physical', 'ep'): self.do_poff_to_extents, ('extent_length', 'esz'): self.do_lengths, ('extent_type', 'et'): self.do_extent_type, ('extent_paths', 'p'): self.do_paths, ('inode_extents', 'ie'): self.do_nr_extents, ('inode_type', 'it'): self.do_inode_type, ('inode_size', 'isz'): self.do_inode_sizes, ('inode_travel_score', 'its'): self.do_travel_scores, ('inode_paths', 'ip'): self.do_paths_stats, } self.done = False self.units = units_auto self.machine = False self.fs = self.fmdb.query_summary()
def __init__(self, session, global_ns): if readline is None: raise RuntimeError('The NICOS console cannot run on platforms ' 'without readline or pyreadline installed.') self.session = session self.log = session.log code.InteractiveConsole.__init__(self, global_ns) self.globals = global_ns for line in DEFAULT_BINDINGS.splitlines(): try: readline.parse_and_bind(line) except IndexError: # raised by pyreadline if the key is unknown pass readline.set_completer(session.completefn) readline.set_history_length(10000) self.histfile = os.environ.get('NICOS_HISTORY_FILE', os.path.expanduser('~/.nicoshistory')) # once compiled, the interactive console uses this flag for all # subsequent statements it compiles self.compile('from __future__ import division') if os.path.isfile(self.histfile): readline.read_history_file(self.histfile)
def main(): parser = argparse.ArgumentParser(description='Interactive PDM reader') parser.add_argument('file', help='PDM file') parser.add_argument('command', nargs=argparse.REMAINDER, help='Command and arguments. Optional') args = parser.parse_args() if not os.path.exists(args.file): print("File not found: " + args.file, file=sys.stderr) return # interactive or one-shot command interactive = not args.command or len(args.command) == 0 schema = PDMParser(args.file).parse() executor = CommandExecutor(schema, interactive) if not interactive: executor.command(' '.join(args.command)) return history_file = os.path.expanduser('~/.pdmreader_history') if os.path.exists(history_file): readline.read_history_file(history_file) try: while True: command: str = input('>>> ').strip() if not command: continue executor.command(command) except Exception as e: readline.set_history_length(1000) readline.write_history_file(history_file) if isinstance(e, EOFError): print() else: raise e