本文整理汇总了Python中readline.read_init_file函数的典型用法代码示例。如果您正苦于以下问题:Python read_init_file函数的具体用法?Python read_init_file怎么用?Python read_init_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_init_file函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:aleasoluciones,项目名称:boscli-oss-core,代码行数:7,代码来源:boscli.py
示例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)
开发者ID:beyang,项目名称:cpython,代码行数:30,代码来源:site.py
示例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)
开发者ID:chubbymaggie,项目名称:octopus-tools,代码行数:9,代码来源:octopus_console.py
示例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
开发者ID:PyreFramework,项目名称:pyre,代码行数:54,代码来源:Interactive.py
示例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))
开发者ID:Tiensbakung,项目名称:interc,代码行数:11,代码来源:autocompleter.py
示例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')
开发者ID:termie,项目名称:zombie,代码行数:12,代码来源:text.py
示例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
开发者ID:batripler,项目名称:config,代码行数:52,代码来源:.py
示例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)
开发者ID:evanunderscore,项目名称:pygnurl,代码行数:51,代码来源:startup.py
示例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.')
开发者ID:DNSGeek,项目名称:xonsh,代码行数:48,代码来源:readline_shell.py
示例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)
开发者ID:zvodd,项目名称:virtualenv,代码行数:47,代码来源:site.py
示例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)
开发者ID:michaelsproul,项目名称:.files,代码行数:17,代码来源:pyrc.py
示例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()
开发者ID:v-legoff,项目名称:accertin,代码行数:44,代码来源:textui.py
示例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)
开发者ID:Emantor,项目名称:pysc,代码行数:44,代码来源:__init__.py
示例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()
开发者ID:jeffbuttars,项目名称:env,代码行数:19,代码来源:pythonrc.py
示例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
开发者ID:ianmiell,项目名称:shutit,代码行数:43,代码来源:shutit_util.py
示例16: shell
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
开发者ID:Omnifarious,项目名称:forthlike,代码行数:20,代码来源:forthlike.py
示例17: __init__
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)
开发者ID:elitegreg,项目名称:pysh,代码行数:21,代码来源:shell.py
示例18: register_readline
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)
开发者ID:mark-nicholson,项目名称:python-editline,代码行数:39,代码来源:sitecustomize.py
示例19: repl
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('>>> ')
开发者ID:Arachnid,项目名称:dapple,代码行数:22,代码来源:deploy.py
示例20: main
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
开发者ID:austinbenincasa,项目名称:PiFiHacker,代码行数:38,代码来源:console.py
注:本文中的readline.read_init_file函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论