def cmd_repl(args): if not validate_phases(args): sys.exit(1) if 'SCAN' in args.phases: regexp = scanner.Regexp.from_files(args.keywords, args.tokens) readline.read_init_file(pathlib.Path.home() / '.inputrc') while True: try: input_text = input(PROMPT) except KeyboardInterrupt: print() continue except EOFError: print() break if input_text == "": continue try: result = process_phases(input_text, args, regexp=regexp, initial_production='single_input') if result is not None: print(result) except ApeError: pass
def init_readline(self): init_file = os.path.expanduser("~/.%s-init" % self.__name) readline.parse_and_bind("set bell-style visible") try: readline.read_init_file(init_file) except IOError: pass
def read_input_config(self): """ Attempts to read readline's input configuration for the user. @return True if a user's configuration was found and read """ # build some basic paths to the readline configurations user_conf = os.path.expanduser('~/.inputrc') host_conf = '/etc/inputrc' # the environment variable should take precedence if 'INPUTRC' in os.environ: init = os.environ['INPUTRC'] # next, check the for a user's custom configuration elif os.path.isfile(user_conf): init = user_conf # finally, see if the host has a basic configuration elif os.path.isfile(host_conf): init = host_conf # no configuration found else: return False # read the init file for the user readline.read_init_file(init) return True
def init_readline(readline: Any) -> None: with suppress(OSError): readline.read_init_file() if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind('tab: complete')
def runCmdLoop(self): ''' Run commands from stdin until close or fini(). ''' import readline readline.read_init_file() while not self.isfini: # if our stdin closes, return from runCmdLoop # FIXME raw_input # FIXME history / completion try: line = get_input(self.cmdprompt) if not line: continue line = line.strip() if not line: continue self.runCmdLine(line) except KeyboardInterrupt as e: self.printf('<ctrl-c>') except EOFError as e: self.fini() except Exception as e: traceback.print_exc()
def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file if 'libedit' in getattr(readline, '__doc__', ''): readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') readline.read_init_file() if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history)
def runCmdLoop(self): ''' Run commands from a user in an interactive fashion until fini() or EOFError is raised. ''' import readline readline.read_init_file() while not self.isfini: # FIXME history / completion try: line = self.get_input() if not line: continue line = line.strip() if not line: continue self.runCmdLine(line) except KeyboardInterrupt as e: self.printf('<ctrl-c>') except (s_common.CliFini, EOFError) as e: self.fini() except Exception as e: s = traceback.format_exc() self.printf(s)
def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file if 'libedit' in getattr(readline, '__doc__', ''): readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history)
def init_readline() -> None: # follow GNU readline config in prompts: system_inputrc_path = '/etc/inputrc' if os.path.exists(system_inputrc_path): readline.read_init_file(system_inputrc_path) user_inputrc_path = os.path.expanduser('~/.inputrc') if os.path.exists(user_inputrc_path): readline.read_init_file(user_inputrc_path)
def real_main(global_opts): readline.read_init_file() print_help_for_seq.allow_pager = False print('Welcome to the kitty shell!') print('Use {} for assistance or {} to quit'.format(green('help'), green('exit'))) while True: try: cmdline = input('🐱 ') except EOFError: break except KeyboardInterrupt: print() continue if not cmdline: continue cmdline = shlex.split(cmdline) cmd = cmdline[0].lower() try: func = cmap[cmd] except KeyError: if cmd in ('exit', 'quit'): break if cmd == 'help': print_help(cmdline[1] if len(cmdline) > 1 else None) continue print_err( '"{}" is an unknown command. Use "help" to see a list of commands.' .format(emph(cmd))) continue try: opts, items = parse_subcommand_cli(func, cmdline) except SystemExit as e: if e.code != 0: print_err(e) print_err('Use "{}" to see how to use this command.'.format( emph('help ' + cmd))) continue except Exception: print_err('Unhandled error:') traceback.print_exc() continue else: try: run_cmd(global_opts, cmd, func, opts, items) except SystemExit as e: print_err(e) continue except KeyboardInterrupt: print() continue except Exception: print_err('Unhandled error:') traceback.print_exc() continue
def init_readline() -> None: global is_libedit with suppress(OSError): readline.read_init_file() if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") is_libedit = True else: readline.parse_and_bind('tab: complete')
def _init_readline(self): readline.parse_and_bind("tab: complete") try: init_file = self.init_file() if init_file: readline.read_init_file(os.path.expanduser(self.init_file())) except FileNotFoundError: pass readline.set_completer(OctopusShellCompleter(self.octopus_shell).complete)
def init_readline(readline): try: readline.read_init_file() except OSError: if not is_macos: raise if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind('tab: complete')
def _init_readline(self): readline.parse_and_bind("tab: complete") try: init_file = self.init_file() if init_file: readline.read_init_file(os.path.expanduser(self.init_file())) except FileNotFoundError: pass readline.set_completer( OctopusShellCompleter(self.octopus_shell).complete)
def pyre_enrich(self, tag): """ Attempt to provide a richer interactive experience """ # attempt to try: # pull readline support import readline, rlcompleter # if unable except ImportError: # is there anything else we can do? return # get the package docstring, gingerly doc = getattr(readline, '__doc__', None) # on OSX, {readline} may be implemented using {libedit} if 'libedit' in doc: # bind the <tab> character to the correct behavior readline.parse_and_bind('bind ^I rl_complete') # otherwise else: # assume gnu {readline} readline.parse_and_bind('tab: complete') # again carefully, try to try: # initialize support readline.read_init_file() # if that fails except OSError: # there are many possible causes; most are unlikely on a well managed system # in all likelihood, it's just that the configuration file doesn't exist # can't do much about any of them, anyway pass # build the uri to the history file history = pyre.primitives.path( '~', f'.{tag}-history').expanduser().resolve() # stringify history = str(history) # attempt to try: # read it readline.read_history_file(history) # if not there except IOError: # no problem pass # make sure it gets saved import atexit # by registering a handler for when the session terminates atexit.register(readline.write_history_file, history) # all done return
def main(): completer = AutoCompleter(['unordered_map', 'unordered_set', 'list', 'print']) readline.set_completer(completer.complete) readline.read_init_file('linereader.rc') while True: line = input('["Q" to quit]: ') if line.strip() == 'Q': break else: completer.learn(parser.tokenize(line))
def __init__( self, definitions, style: str, want_readline: bool, want_completion: bool, use_unicode: bool, prompt: bool, ): super(TerminalShellGNUReadline, self).__init__( definitions, style, want_completion, use_unicode, prompt ) # Try importing readline to enable arrow keys support etc. self.using_readline = False self.history_length = definitions.get_config_value("$HistoryLength", HISTSIZE) if have_full_readline and want_readline: self.using_readline = sys.stdin.isatty() and sys.stdout.isatty() self.ansi_color_re = re.compile("\033\\[[0-9;]+m") if want_completion: set_completer( lambda text, state: self.complete_symbol_name(text, state) ) self.named_character_names = set(named_characters.keys()) # Make _ a delimiter, but not $ or ` # set_completer_delims(RL_COMPLETER_DELIMS) set_completer_delims(RL_COMPLETER_DELIMS_WITH_BRACE) # GNU Readling inputrc $include's paths are relative to itself, # so chdir to its directory before reading the file. parent_dir = pathlib.Path(__file__).parent.absolute() with parent_dir: inputrc = "inputrc-unicode" if use_unicode else "inputrc-no-unicode" try: read_init_file(str(parent_dir / inputrc)) except: # noqa pass parse_and_bind("tab: complete") self.completion_candidates = [] # History try: read_history_file(HISTFILE) except IOError: pass except: # noqa # PyPy read_history_file fails pass set_history_length(self.history_length) atexit.register(self.user_write_history_file)
def init_readline(self): """Activates history and tab completion """ # - 1. history stuff # - mainly borrowed from site.enablerlcompleter() from py3.4+, # we can't simply call site.enablerlcompleter() because its # implementation overwrites the history file for each python # session whereas we prefer appending history from every # (potentially concurrent) session. # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass def append_history(len_at_start): current_len = readline.get_current_history_length() readline.append_history_file(current_len - len_at_start, config.HISTFILE) if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # see: http://bugs.python.org/issue5845#msg198636 try: readline.read_history_file(config.HISTFILE) except IOError: pass len_at_start = readline.get_current_history_length() atexit.register(append_history, len_at_start) readline.set_history_length(config.HISTSIZE) # - 2. enable auto-indenting if config.AUTO_INDENT: readline.set_pre_input_hook(self.auto_indent_hook) # - 3. completion # - replace default completer self.completer = ImprovedCompleter(self.locals) readline.set_completer(self.completer.complete)
def pyre_enrich(self, tag): """ Attempt to provide a richer interactive experience """ # attempt to try: # pull readline support import readline, rlcompleter # if unable except ImportError: # is there anything else we can do? return # get the package docstring, gingerly doc = getattr(readline, '__doc__', None) # on OSX, {readline} may be implemented using {libedit} if 'libedit' in doc: # bind the <tab> character to the correct behavior readline.parse_and_bind('bind ^I rl_complete') # otherwise else: # assume gnu {readline} readline.parse_and_bind('tab: complete') # again carefully, try to try: # initialize support readline.read_init_file() # if that fails except OSError: # there are many possible causes; most are unlikely on a well managed system # in all likelihood, it's just that the configuration file doesn't exist # can't do much about any of them, anyway pass # build the uri to the history file history = pyre.primitives.path('~', f'.{tag}-history').expanduser().resolve() # stringify history = str(history) # attempt to try: # read it readline.read_history_file(history) # if not there except IOError: # no problem pass # make sure it gets saved import atexit # by registering a handler for when the session terminates atexit.register(readline.write_history_file, history) # all done return
def _setup_readline(self): try: readline.read_init_file('.readlinerc') except IOError: pass try: readline.read_history_file('.zombiehist') except IOError: pass atexit.register(readline.write_history_file, '.zombiehist')
def do_readline(): import os, os.path, re, keyword, __main__; from six.moves import builtins def get_class_members(klass): r=dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: r=r+get_class_members(base) return r class Completer: def __init__(self, ns=None): if ns is None: ns=__main__.__dict__ assert isinstance(ns,dict); self.ns=ns def complete(self, text, state): if state==0: if '.' in text: self.matches=self.attr_matches(text) else: self.matches=self.global_matches(text) try: return self.matches[state] except IndexError: return None def global_matches(self, text): matches=[]; n=len(text) for word in keyword.kwlist: if word[:n]==text: matches.append(word) for nspace in [builtins.__dict__, self.ns]: for word,val in nspace.items(): if word[:n]==text and word!='__builtins__': matches.append(word) return matches def attr_matches(self, text): m=re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return [] expr,attr=m.group(1,3) try: thisobject=eval(expr,self.ns) except Exception: return [] words=dir(thisobject); matches = []; n=len(attr) for word in words: if word[:n]==attr and word!='builtins': matches.append("%s.%s"%(expr,word)) return matches try: import rlcompleter, readline initfile=os.environ.get('INPUTRC') or os.path.expanduser('~/.inputrc') histfile=os.path.expanduser('~/.python-history') if os.path.exists(initfile): readline.read_init_file(initfile) readline.set_completer(Completer().complete) try: readline.read_history_file(histfile) except IOError: pass def savehist(): histfilesize=os.environ.get('HISTFILESIZE') or os.environ.get('HISTSIZE') if histfilesize: try: readline.set_history_length(int(histfilesize)) except ValueError: pass readline.write_history_file(histfile) import atexit; atexit.register(savehist) readline.parse_and_bind('tab: complete') except (ImportError,AttributeError): pass
def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except OSError: pass def write_history(): try: readline.write_history_file(history) except OSError as e: if isinstance(e, (FileNotFoundError, PermissionError)): # home directory does not exist or is not writable # https://bugs.python.org/issue19891 pass elif isinstance(e, (OSError)) and e.errno == -1: print("Warning: unable to write into .python_history") else: raise atexit.register(write_history)
def register_readline(): """Initialise readline history and completion. This function was taken from Python 3.5.0 with minor changes so it runs on older versions (readline raises IOError which was merged with OSError in 3.3, so we need to adjust references to OSError to check for IOError instead). >>> import inspect >>> import sys >>> source = inspect.getsource(sys.__interactivehook__) >>> source = source.replace('OSError', 'IOError') >>> print(source) """ import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except IOError: # An IOError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history)
def register_readline(): import atexit try: import readline except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = "" if "XDG_CACHE_HOME" in os.environ: history = Path(os.environ["XDG_CACHE_HOME"]) / "python" / "history" history.parent.mkdir(parents=True, exist_ok=True) else: history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except OSError: pass def write_history(): try: readline.write_history_file(history) except OSError: # bpo-19891, bpo-41193: Home directory does not exist # or is not writable, or the filesystem is read-only. pass atexit.register(write_history)
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') # Cygwin seems to hang indefinitely when querying the readline lib if (not ON_CYGWIN) and (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") # try to load custom user settings try: readline.read_init_file() except Exception: # this seems to fail with libedit print_exception('xonsh: could not load readline default init file.')
def run_repl(): readline.read_init_file(READLINERC) while True: line = input(PROMPT) if line == "exit": break try: regex, word = line.split(":") except: print("Incorrect input format") exit(1) print(RE(Parser(regex).parse()).match(word))
def register_readline(): import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, "__doc__", "") if readline_doc is not None and "libedit" in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser("~"), ".python_history") try: readline.read_history_file(history) except OSError: pass 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 atexit.register(write_history)
def util_raw_input(prompt='', default=None, ispass=False, use_readline=True): """Handles raw_input calls, and switches off interactivity if there is apparently no controlling terminal (or there are any other problems) """ if use_readline: try: readline.read_init_file('/etc/inputrc') except IOError: pass readline.parse_and_bind('tab: complete') prompt = '\r\n' + prompt if ispass: prompt += '\r\nInput Secret: ' sanitize_terminal() if shutit_global.shutit_global_object.interactive == 0: return default # See: https//github.com/ianmiell/shutit/issues/299 - python3 made input == python 2's raw_input if not PY3: try: input = raw_input except NameError: pass # input should be set/available by this point - if not, there is a problem. try: input except NameError: print('input not available, printing debug') print_debug() sys.exit(1) if not shutit_global.shutit_global_object.determine_interactive(): return default while True: try: if ispass: return getpass.getpass(prompt=prompt) else: return input(prompt).strip() or default except KeyboardInterrupt: continue except IOError: msg = 'Problems getting raw input, assuming no controlling terminal.' if ispass: return getpass.getpass(prompt=prompt) else: return input(prompt).strip() or default shutit_global.shutit_global_object.set_noninteractive(msg=msg) return default
def init_readline(self): """Activates history and tab completion """ # - mainly borrowed from site.enablerlcompleter() from py3.4+ # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # see: http://bugs.python.org/issue5845#msg198636 try: readline.read_history_file(config['HISTFILE']) except IOError: pass atexit.register(readline.write_history_file, config['HISTFILE']) readline.set_history_length(config['HISTSIZE']) # - replace default completer readline.set_completer(self.improved_rlcompleter()) # - enable auto-indenting if config['AUTO_INDENT']: readline.set_pre_input_hook(self.auto_indent_hook) # - remove '/' and '~' from delimiters to help with path completion completer_delims = readline.get_completer_delims() completer_delims = completer_delims.replace('/', '') if config.get('COMPLETION_EXPANDS_TILDE'): completer_delims = completer_delims.replace('~', '') readline.set_completer_delims(completer_delims)
def enable_history(self): """Enable history completion (stolen from site.py)""" try: readline.read_init_file() except: pass if readline.get_current_history_length() == 0: home = os.path.expanduser("~") history = os.path.join(home, ".python_history") try: readline.read_history_file(history) except: pass readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, history)
def prepare(): global LOGLEVEL global log, sDir, sHome sHome = os.path.expanduser('~') sDir = os.path.split(__name__)[0] if (sDir): os.chdir(sDir) if ('readline' in globals()): sInputrc = os.path.join(sHome, '.inputrc') if (os.path.isfile(sInputrc)): readline.read_init_file(sInputrc) sInputrc = '/etc/inputrc' if (os.path.isfile(sInputrc)): readline.read_init_file(sInputrc) logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(LOGLEVEL) socket.setdefaulttimeout(30)
def _setup_readline(): if not readline: return False for h in ht3.history.get_history(): readline.add_history(h) completion_cache = [] def rl_complete(text, n): if n == 0: try: # rl consumes entire list, so no lazy evaluation possible completion_cache.clear() completion_cache.extend(complete_command_with_args(text)) except Exception as e: # readline ignores all exceptions ht3.lib.EXCEPTION_HOOK(exception=e) return completion_cache[n] readline.set_completer(rl_complete) readline.set_completer_delims("") # complete with the whole line readline.parse_and_bind("tab: complete") readline.read_init_file() if signal: class StdOutWrapper(): def __init__(self, wrapped): self.wrapped = wrapped self.prompt = True def write(self, s): if self.prompt: self.wrapped.write('\r\x1b[K') self.prompt = False self.wrapped.write(s) if s == "\n": os.kill(os.getpid(), signal.SIGWINCH) self.prompt = True def __getattr__(self, a): return getattr(self.wrapped, a) sys.stdout = StdOutWrapper(sys.stdout)
def runui(self): global HELP_TEXT exported.add_help("textui", HELP_TEXT) exported.write_message("For textui help, type \"#help textui\".") # termios is the module that allows us to change echo for a terminal # but only if the module is present try: import termios except ImportError: self._tio = 0 else: self._tio = 1 echonew = termios.tcgetattr(self._stdin.fileno()) self._onecho_attr = echonew[3] self._offecho_attr = echonew[3] & ~termios.ECHO if config.options.has_key("readline"): try: import readline except ImportError: self._rline = 0 exported.write_error("Readline not available for your system.") else: self._rline = 1 # we do some stuff to grab the readlinerc file if they have one # so the user can set some readline oriented things which makes # things a little nicer for the user. d = exported.get_config("datadir") try: readline.read_init_file(d + "readlinerc") except: exported.write_error( "Note: No readlinerc file available in %s." % d) exported.write_message("Readline enabled.") if self._tio == 0 or self._rline == 1: exported.write_error("Warming: echo off is unavailable. " + "Your password will be visible.") # go into the main loop self.run()
def runui(self): global HELP_TEXT exported.add_help("textui", HELP_TEXT) exported.write_message("For textui help, type \"#help textui\".") # termios is the module that allows us to change echo for a terminal # but only if the module is present try: import termios except ImportError: self._tio = 0 else: self._tio = 1 echonew = termios.tcgetattr(self._stdin.fileno()) self._onecho_attr = echonew[3] self._offecho_attr = echonew[3] & ~termios.ECHO if config.options.has_key("readline"): try: import readline except ImportError: self._rline = 0 exported.write_error("Readline not available for your system.") else: self._rline = 1 # we do some stuff to grab the readlinerc file if they have one # so the user can set some readline oriented things which makes # things a little nicer for the user. d = exported.get_config("datadir") try: readline.read_init_file(d + "readlinerc") except: exported.write_error("Note: No readlinerc file available in %s." % d) exported.write_message("Readline enabled.") if self._tio == 0 or self._rline == 1: exported.write_error("Warming: echo off is unavailable. " + "Your password will be visible.") # go into the main loop self.run()
def start(*k, **kw): global CONSOLE try: import rlcompleter import readline except ImportError: rlcompleter = None readline = None histfile = os.path.join(os.environ["HOME"], ".socrocket_history") rcfile = os.path.join(os.environ["HOME"], ".socrocketrc") if not CONSOLE: if not readline: print("Python shell enhancement modules not available.") else: if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") if os.path.isfile(histfile): readline.read_history_file(histfile) if os.path.isfile(rcfile): readline.read_init_file(rcfile) print("Python shell history and tab completion are enabled.") sys.modules['__main__'].__dict__.update({ "help": help_text, "credits": credits_text, "copyright": copyright_text, "license": license_text }) CONSOLE = Console(sys.modules['__main__'].__dict__) sys.modules['__main__'].__dict__['CONSOLE'] = CONSOLE CONSOLE.interact('') if readline: readline.write_history_file(histfile)
def run(recorder, prompt_color=True, prompt_on_misc=True, enable_misc_cmd=True): try: readline.read_init_file() except Exception: # for some reason this fails on MacOS pass prompt = "\x1b[31m(rec)\x1b[0m " if prompt_color else "(rec) " multiline_prompt = "\x1b[31m>\x1b[0m " if prompt_color else "> " try: while True: cmd = input(prompt) # parse multiline commands and display a different prompt to denote # we're in multiline mode similarly to how bash does it if len(cmd) > 0 and cmd[-1] == "\\": parts = [cmd[:-1]] while True: part = input(multiline_prompt) if len(part) > 0 and part[-1] == "\\": parts.append(part[:-1]) continue parts.append(part) break cmd = " ".join(parts) split_cmd = shlex.split(cmd) if len(split_cmd) == 0: continue if split_cmd[0] == "aws": recorder.run_aws_cmd(split_cmd[1:]) else: if not enable_misc_cmd: print("Can only record awscli commands.") continue run_misc_cmd(cmd, prompt_on_misc) except EOFError: pass except KeyboardInterrupt: pass print("")
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 util_raw_input(prompt='', default=None, ispass=False, use_readline=True): """Handles raw_input calls, and switches off interactivity if there is apparently no controlling terminal (or there are any other problems) """ if use_readline: try: readline.read_init_file('/etc/inputrc') except IOError: pass readline.parse_and_bind('tab: complete') prompt = '\r\n' + prompt if ispass: prompt += '\r\nInput Secret: ' sanitize_terminal() if shutit_global.shutit_global_object.interactive == 0: return default ## See: https//github.com/ianmiell/shutit/issues/299 - python3 made input == python 2's raw_input #if not shutit_global.shutit_global_object.ispy3: # input = raw_input #try: # input #except NameError: # shutit_global.shutit_global_object.shutit_print('input not available, printing debug') # print_debug() # sys.exit(1) if not shutit_global.shutit_global_object.determine_interactive(): return default while True: try: if ispass: return getpass.getpass(prompt=prompt) else: return input(prompt).strip() or default except KeyboardInterrupt: continue except IOError: msg = 'Problems getting raw input, assuming no controlling terminal.' if ispass: return getpass.getpass(prompt=prompt) else: return input(prompt).strip() or default shutit_global.shutit_global_object.set_noninteractive(msg=msg) return default
def custom_interactivehook(): """ mostly copied from lib/python3.8/site.py """ import atexit try: import readline import rlcompleter except ImportError: return readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass #if readline.get_current_history_length() == 0: # history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except OSError: pass 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 atexit.register(write_history)
def register_readline(): import atexit import os import readline import rlcompleter from pathlib import Path # Reading the initialization (config) file may not be enough to set a completion key, so we set # one first and then read the file. readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one is that there's no # .inputrc file. In that case, we want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to $XDG_CACHE_HOME/python/history. The guard is # necessary to avoid doubling history size at each interpreter exit when readline was # already configured through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 cache_home = Path(os.environ.get('XDG_CACHE_HOME', '~/.cache')).expanduser() history = cache_home / 'python/history' try: readline.read_history_file(history) except OSError: pass def write_history(): try: os.makedirs(history.parent, exist_ok=True) readline.write_history_file(history) except OSError: # bpo-19891, bpo-41193: Config home directory does not exist or is not writable, or # the filesystem is read-only. pass atexit.register(write_history)
def shell(interp): readline.read_init_file() readline.set_history_length(500) try: while True: x = raw_input("star> ") msg = None try: interp.run(shlex.split(x)) except KeyError: msg = "does not exist" except: sys.excepthook(*sys.exc_info()) msg = "parse error!" if msg != None: print " =>",msg,"\n" else: print " => %r\n" % (interp.get_stack(),) except (EOFError, KeyboardInterrupt): print
def __init__(self): self.__inputrc = os.path.join(os.path.expanduser('~'), '.inputrc') self.__histfile = os.path.join(os.path.expanduser('~'), '.pysh-history') if os.path.exists(self.__inputrc): readline.read_init_file(self.__inputrc) if os.path.exists(self.__histfile): readline.read_history_file(self.__histfile) self.__children = [] self.__pid = os.getpid() if _terminal.interactive: _terminal.loop_until_foreground(os.getpgrp()) ignore_signals() os.setpgid(self.__pid, self.__pid) _terminal.grab_control(self.__pid) _terminal.save_attributes() _terminal.shell_pgid = os.getpgid(self.__pid)
def repl(): # REPL! # readline adds extra features to the # input function, such as input history. import readline try: readline.read_init_file('.dapple.rc') except Exception: print("No valid .dapple.rc in current directory. Using defaults.") scope = Scope() build = plugins.load('core.build')('repl') runner = DeployScript(None, build, None) print("REPL engaged. Enter `exit` to quit.") line = '' while line.lower() != 'exit': if line.strip(): print(runner.run_line(line, scope)) line = raw_input('>>> ')
def register_readline(): """Attempt to configure the readline completion support""" import atexit try: import readline import rlcompleter except ImportError: return # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # through a PYTHONSTARTUP hook, see: # http://bugs.python.org/issue5845#msg198636 history = os.path.join(os.path.expanduser('~'), '.python_history') try: readline.read_history_file(history) except IOError: pass atexit.register(readline.write_history_file, history)
def main(): run = True # setting up command history try: readline.read_history_file(cmd_history) readline.set_history_length(1000) except Exception: open("cmd_history", "a") readline.read_init_file(cmd_history) if os.path.isfile("config.txt"): pass else: puts(colored.cyan("Setting up PiFiHacker for you...")) instance = setup() instance.setup() puts(colored.cyan("PiFiHacker has been successfully setup")) instance = command() while run: try: cmd = raw_input(colored.green("PiFiHacker:~$ ")) readline.write_history_file(cmd_history) if cmd: readline.write_history_file(cmd_history) output = instance.proccess_command(cmd) if output == False: run = False if output is not None: if "1" == output[0]: puts(colored.red(output[1])) else: puts(output) else: cmd = raw_input(colored.green("PiFiHacker:~$ ")) except KeyboardInterrupt: run = False readline.write_history_file(cmd_history) print
# So we go there immediately. Realpath is used in case we are launched with # a symbolic link. os.chdir( os.path.dirname( os.path.realpath(__file__) ) ) # Local from mi_API import API from mi_Session import Session # Diagnostic import pdb # Constants READLINE_INIT_FILE = ".inputrc" # Set up readline readline.read_init_file( os.path.join( os.path.expanduser('~'), READLINE_INIT_FILE ) ) interactive = False cmd_files = None piped_input = False diagnostic = False verbose = False if __name__ == '__main__': # Process command line args from sys import argv, stdin if not stdin.isatty(): piped_input = True if len(argv) > 1: if '-i' in argv[1:]: interactive = True
#!/usr/bin/env python3 import os import readline import shutil import subprocess import sys import tempfile from autocompleter import AutoCompleter import parser completer = AutoCompleter() readline.set_completer(completer.complete) readline.read_init_file('linereader.rc') default_dir = os.path.join(tempfile.gettempdir(), 'interc') o_start = 0 SRC = 'a.cc' CXX = 'clang++' CXXFLAGS = '-std=c++11 -O2' BIN = 'a.out' headers = set([ '#include <array>', '#include <bitset>', '#include <deque>', '#include <forward_list>', '#include <list>', '#include <map>', '#include <queue>',
Show the usc command prompt usc host (port) Starts usc and tries to connect to host usc alias Starts usc and tries to connect to a known (host[, port]) alias """ if __name__ == "__main__": completer_filename = os.path.expanduser("~/.usc_completer.rc") aliases = usc_config.get_aliases() readline.read_init_file(completer_filename) if len(sys.argv) > 1: # Directly connects (host, port) = usc_config.resolve_addr(sys.argv[1:]) usc = controller.UscController() usc.connect(host, port) else: # Starts a usc shell shell = usc_shell.UscShell() shell.start()
"""Read a line of input from stdin and return it. If nothing is read, the default value is returned. Note that if stdin in not a TTY, the label will not be displayed.""" if sys.stdin.isatty(): if defaultValue: label += " [%s]" % defaultValue label += ": " if password: result = getpass.getpass(label) else: if sys.platform == "win32": import msvcrt for c in label: msvcrt.putch(c) result = sys.stdin.readline().strip() else: result = raw_input(label).strip() else: result = raw_input().strip() if not result: return defaultValue return result # set up readline capability, if applicable try: import readline readline.read_init_file() except: pass
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import os, sys, readline get_input = input if sys.version_info[:2] <= (2, 7): get_input = raw_input try: readline.read_init_file(os.path.join(os.path.expanduser('~'), 'pedit.rc')) except IOError: readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode emacs') if __name__ == '__main__': try: filename = sys.argv[1] except IndexError: print("git config --global core.editor {}".format(sys.argv[0])) sys.exit(1) print('Enter commit message bellow. Terminate with an empty line.') with open(filename, 'w') as file_obj: try: sentinel = b'' message = b'\n'.join(iter(get_input, sentinel)) except KeyboardInterrupt: print("Canceled") sys.exit(1)
yield i continue yield arg def complete(self,text,state): text = text.replace('%','\\%').replace('_','\\_') self.cur.execute('SELECT key FROM cmd WHERE key LIKE ? ORDER BY key LIMIT 1 OFFSET ?',(text+'%',state)) try: return self.cur.fetchone()[0] except TypeError: return if __name__ == '__main__': import os, imp, platform, getpass shell = Shell() try: readline.read_init_file('dot-ppyrc') except IOError: try: readline.read_init_file('/etc/ppy.ppyrc') except IOError: pass try: readline.read_history_file('dot-ppyhist') except IOError: pass atexit.register(readline.write_history_file,'dot-ppyhist') readline.set_completer(shell.complete) readline.parse_and_bind('tab: complete') try: while True: try:
self.candidates = [ w+' ' for w in candidates if w.startswith(being_completed) ] else: self.candidates = candidates except err: self.candidates = [] try: response = self.candidates[state] except IndexError: reponse = None return response """ Exemples : com = Completer({ "entry" : { "list" : ["names"], "stop":[] }, "names" : { "bob" : [], "jack" : [] } }, "entry") readline.read_init_file("usc.rc") readline.set_completer(com.complete) s = input("> ") """
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import readline readline.read_init_file('myreadline.rc') while True: line = raw_input('Prompt ("stop" to quit): ') if line == 'stop': break print 'ENTERED: "%s"' % line
import platform sys.ps1 = ">>> " sys.ps2 = " " historyPath = os.path.expanduser("~/.python/history") inputrcPath = os.path.expanduser("~/.python/inputrc") if os.path.exists(historyPath): readline.read_history_file(historyPath) def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) atexit.register(save_history) # Try to guess if this is an Apple-shipped Python, which will have GNU # Readline replaced with editline. if platform.python_compiler().endswith("(tags/Apple/clang-418.0.60)"): readline.parse_and_bind("bind ^I rl_complete") else: if os.path.exists(inputrcPath): readline.read_init_file(inputrcPath) del sys, os, atexit, readline, rlcompleter, platform