本文整理汇总了Python中readline.read_history_file函数的典型用法代码示例。如果您正苦于以下问题:Python read_history_file函数的具体用法?Python read_history_file怎么用?Python read_history_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_history_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_readline
def setup_readline():
histfile = os.path.join(os.path.expanduser("~"), ".flux_robot_history")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
示例2: Interact
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)
示例3: interactive
def interactive(self):
try:
readline.read_history_file(Debugger.HISTORY_FILE)
except IOError:
pass
cpu = self.cpu
try:
while True:
cmd,args = self.prompt()
if cmd in 'xq':
return
elif cmd == 's':
cpu.step()
elif cmd == 'k':
self.stack(args)
elif cmd == 'b':
self.breakpoint(args)
elif cmd == 'r':
self.run()
elif cmd == 'ret':
self.runUntilRet()
elif cmd == '?':
self.evalPrint(args)
elif cmd == 'l':
self.listSource(args)
else:
print 'Unknown command! (%s)' % cmd
finally:
readline.write_history_file(Debugger.HISTORY_FILE)
示例4: init_history
def init_history(self):
histfile=os.path.expanduser("~/.%s-history" % self.__name)
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(self.save_history, histfile)
示例5: run_classic_shell
def run_classic_shell(locals, globals, first_time):
if first_time:
banner = "Hit Ctrl-D to return to PuDB."
else:
banner = ""
ns = SetPropagatingDict([locals, globals], locals)
from pudb.settings import get_save_config_path
from os.path import join
hist_file = join(
get_save_config_path(),
"shell-history")
if HAVE_READLINE:
readline.set_completer(
rlcompleter.Completer(ns).complete)
readline.parse_and_bind("tab: complete")
try:
readline.read_history_file(hist_file)
except IOError:
pass
from code import InteractiveConsole
cons = InteractiveConsole(ns)
cons.interact(banner)
if HAVE_READLINE:
readline.write_history_file(hist_file)
示例6: _init_history_file
def _init_history_file(self):
if hasattr(readline, "read_history_file"):
try:
readline.read_history_file(self.history_file)
except FileNotFoundError:
pass
atexit.register(self.save_history)
示例7: _test_main
def _test_main():
import os
import readline
import atexit
# Setup history and readline facility for remote q:
histfile = os.path.join(os.environ['HOME'], '.pyhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
conn = connect()
print('"conn" is your handle to rserve. Type e.g. "conn(\'1\')" '
'for string evaluation.')
# r('x<-1:20; y<-x*2; lm(y~x)')
sc = open('../testData/test-script.R').read()
v = conn.r(sc)
open('r-test-png.png', 'w').write(v[3])
conn.r.v = 'abc'
conn.r('func0 <- function() { 3 }')
conn.r('func1 <- function(a1) { a1 }')
conn.r('func2 <- function(a1, a2) { list(a1, a2) }')
conn.r('funcKW <- function(a1=1, a2=4) { list(a1, a2) }')
conn.r('squared<-function(t) t^2')
示例8: exec_cmdloop
def exec_cmdloop(self, args, options):
try:
import readline
delims = readline.get_completer_delims()
delims = delims.replace(':', '') # "group:process" as one word
delims = delims.replace('*', '') # "group:*" as one word
delims = delims.replace('-', '') # names with "-" as one word
readline.set_completer_delims(delims)
if options.history_file:
try:
readline.read_history_file(options.history_file)
except IOError:
pass
def save():
try:
readline.write_history_file(options.history_file)
except IOError:
pass
import atexit
atexit.register(save)
except ImportError:
pass
try:
self.cmdqueue.append('status')
self.cmdloop()
except KeyboardInterrupt:
self.output('')
pass
示例9: enable_readline
def enable_readline():
"""
Imports the `readline` module to enable advanced repl text manipulation,
and command history navigation.
Returns True if success, otherwise False.
"""
try:
import readline
except ImportError:
return False
import os
import atexit
histfile = os.path.join(os.path.expanduser("~"), ".clojurepyhist")
if not os.path.isfile(histfile):
with open(histfile, 'a'):
os.utime(histfile, None)
os.chmod(histfile, int('640',8))
try:
readline.read_history_file(histfile)
except IOError:
# Pass here as there isn't any history file, so one will be
# written by atexit
pass
atexit.register(readline.write_history_file, histfile)
return True
示例10: rlinput
def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
"""
Get user input with readline editing support.
"""
sentinel = ''
if prefill is None:
prefill = ''
def only_once(text):
""" generator for startup hook """
readline.insert_text(text)
yield
while True:
yield
savedhist = NamedTemporaryFile()
readline.write_history_file(savedhist.name)
ctxhistname = ".tl" + ctxkey + "history"
ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
try:
readline.clear_history()
except AttributeError:
print "This readline doesn't support clear_history()"
raise
savedcompleter = readline.get_completer()
try:
ulines = uniqify(ctxhistfile)
readline.read_history_file(ctxhistfile)
readline.set_completer(HistoryCompleter(ulines).complete)
except IOError:
pass
readline.parse_and_bind('tab: complete')
saveddelims = readline.get_completer_delims()
readline.set_completer_delims('') ## No delims. Complete entire lines.
readline.set_completion_display_matches_hook(match_display_hook)
gen = only_once(prefill)
readline.set_startup_hook(gen.next)
try:
if oneline:
edited = raw_input(prompt)
else:
print prompt
edited = "\n".join(iter(raw_input, sentinel))
if edited.endswith(r'%%'):
## Invoke external editor
edited = external_edit(edited[0:-2])
return edited
finally:
## Restore readline state
readline.write_history_file(ctxhistfile)
readline.clear_history()
readline.read_history_file(savedhist.name)
savedhist.close()
readline.set_completer(savedcompleter)
readline.set_completer_delims(saveddelims)
readline.set_startup_hook()
示例11: get_input_with_readline
def get_input_with_readline(filename):
"""
sets up readline support for entering sitenames, completed from the
existing list and accepts a line of input.
"""
if not os.path.exists(filename):
file(filename, "w").close()
all_lines = map(lambda x: x.strip(), file(filename).readlines())
def completer(text, state):
"""
custom readline completer
"""
candidates = filter(lambda x: x.startswith(text), all_lines)
if state <= len(candidates):
return candidates[state-1]
else:
return None
try:
import readline
readline.set_completer(completer)
readline.read_history_file(filename)
readline.parse_and_bind('tab: complete')
if hasattr(readline, 'readline'):
print "sitename: ",
readline._issued = True
return readline.readline(history=all_lines, histfile=None)
else:
return raw_input("sitename: ")
except:
# no readline?
return raw_input("sitename: ")
示例12: main
def main(argv):
parser = optparse.OptionParser()
parser.add_option('-s', '--server', dest='server',
help='The hostname your app is deployed on. '
'Defaults to <app_id>.appspot.com.')
(options, args) = parser.parse_args()
if not args or len(args) > 2:
print >> sys.stderr, __doc__
if len(args) > 2:
print >> sys.stderr, 'Unexpected arguments: %s' % args[2:]
sys.exit(1)
appid = args[0]
if len(args) == 2:
path = args[1]
else:
path = DEFAULT_PATH
remote_api_stub.ConfigureRemoteApi(appid, path, auth_func,
servername=options.server)
remote_api_stub.MaybeInvokeAuthentication()
readline.parse_and_bind('tab: complete')
atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
sys.ps1 = '%s> ' % appid
if os.path.exists(HISTORY_PATH):
readline.read_history_file(HISTORY_PATH)
code.interact(banner=BANNER, local=globals())
示例13: setup
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")
示例14: __enter__
def __enter__(self):
if readline_loaded:
if readline.__doc__ and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind '\t' rl_complete") # Enable tab completions on MacOS
else:
readline.parse_and_bind("tab: complete") # and on other OSs
readline.parse_and_bind("set completion-ignore-case on")
readline.parse_and_bind("set show-all-if-ambiguous on")
readline.parse_and_bind("set completion-map-case on")
readline.parse_and_bind("set show-all-if-unmodified on")
readline.parse_and_bind("set expand-tilde on")
history_file_dir = appdirs.user_data_dir(self.this_program_name, self.this_program_name)
os.makedirs(history_file_dir, exist_ok=True)
self.history_file_path = os.path.join(history_file_dir, "." + self.this_program_name + "_console_history")
try:
readline.read_history_file(self.history_file_path)
except Exception: # Corrupt or non existent history file might raise an exception
try:
os.remove(self.history_file_path)
except Exception:
pass # if removing the file also fail - just ignore it
if colorama_loaded:
colorama.init()
self.prompt = self.this_program_name + ": "
self.save_dir = os.getcwd()
return self
示例15: main
def main(args=None, options=None):
if options is None:
options = ClientOptions()
options.realize(args, doc=__doc__)
c = Controller(options)
if options.args:
c.onecmd(" ".join(options.args))
if options.interactive:
try:
import readline
if options.history_file:
try:
readline.read_history_file(options.history_file)
except IOError:
pass
def save():
try:
readline.write_history_file(options.history_file)
except IOError:
pass
import atexit
atexit.register(save)
except ImportError:
pass
try:
c.cmdqueue.append('status')
c.cmdloop()
except KeyboardInterrupt:
c.output('')
pass