本文整理汇总了Python中readline.read_init_file函数的典型用法代码示例。如果您正苦于以下问题:Python read_init_file函数的具体用法?Python read_init_file怎么用?Python read_init_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_init_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_readline
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
示例2: register_readline
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)
示例3: _init_readline
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)
示例4: pyre_enrich
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
示例5: main
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))
示例6: _setup_readline
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')
示例7: do_readline
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
示例8: register_readline
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)
示例9: setup_readline
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.')
示例10: register_readline
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)
示例11: enable_history
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)
示例12: runui
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()
示例13: start
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)
示例14: init_readline
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()
示例15: util_raw_input
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