本文整理汇总了Python中readline.write_history_file函数的典型用法代码示例。如果您正苦于以下问题:Python write_history_file函数的具体用法?Python write_history_file怎么用?Python write_history_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_history_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _save_history
def _save_history(self, history_file):
"""
Save the commandline history to the readline history provided
+ Clear the history buffer
"""
readline.write_history_file(os.path.join(MODULE_LOCATION, history_file))
readline.clear_history()
示例2: run_shell
def run_shell(self):
do_readline = sys.stdin.isatty() and ('-', sys.stdin) in self.files
if do_readline and os.path.exists(os.path.expanduser('~/.fsh_history')):
readline.read_history_file(os.path.expanduser('~/.fsh_history'))
for file in ('/etc/inputrc', os.path.expanduser('~/.inputrc')):
if os.path.exists(file):
with open(file) as fd:
readline.parse_and_bind(fd.read())
while self.files:
self.curfile, self.curfd, self.curline = self.files[0]
self.files = self.files[1:]
if self.verbose:
print "%s(Now processing %s)" % (self.ps4, self.curfile)
try:
while True:
line = self.get_input()
if not line:
break
if self.verbose:
print '%s%s (%s, line %d)' % (self.ps4, line, self.curfile, self.curline)
self.parse_and_run(line)
except:
if do_readline:
readline.write_history_file(os.path.expanduser('~/.fsh_history'))
raise
if do_readline:
readline.write_history_file(os.path.expanduser('~/.fsh_history'))
示例3: main_loop
def main_loop(self):
readline.parse_and_bind('tab: complete')
readline.set_completer(self.rl_completer_safe)
#print 'delims: ', repr(readline.get_completer_delims())
hist_file = os.path.expanduser("~/.qadmin_history")
try:
readline.read_history_file(hist_file)
except IOError:
pass
print "Use 'show help;' to see available commands."
while 1:
try:
ln = self.line_input()
self.exec_string(ln)
except KeyboardInterrupt:
print
except EOFError:
print
break
self.reset_comp_cache()
try:
readline.write_history_file(hist_file)
except IOError:
pass
示例4: do_exit
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
示例5: SaveInteractiveSession
def SaveInteractiveSession(filename='interactiveSession.py',path=output_dir):
"""
Save the interactive session
Input:
- *filename*: [default = interactiveSession.py'] (string)
- *path*: (string)
"""
if not _IsReadline:
print("Error: install 'readline' first")
elif _IsReadline:
historyPath = os.path.join(path,filename)
if not os.path.exists(path):
os.makedirs(directory)
readline.write_history_file(historyPath)
file_in = open(historyPath,'r')
history_list = file_in.readlines()
n_import_statement = 0
for command in history_list:
if 'import' in command and 'stochpy' in command:
n_import_statement +=1
n=0
file_out = open(historyPath,'w')
for command in history_list:
if 'import' in command and 'stochpy' in command:
n+=1
if n==n_import_statement:
file_out.write(command)
file_out.close()
print("Info: Interactive session successfully saved at {0:s}".format(historyPath) )
print("Info: use 'ipython {0:s} to restart modeling with this interactive session".format(filename) )
示例6: main
def main(debug):
print("type exit to quit repl")
if os.path.exists(HISTORY):
readline.read_history_file(HISTORY)
q = Query(debug=debug)
try:
while True:
l = input("> ").lstrip("/")
if not l:
continue
elif l == "exit":
break
else:
try:
res = q.query("repl", l)
except Exception as e:
print(str(e))
traceback.print_tb(e.__traceback__)
continue
if res.message:
print(res.message.strip())
elif res.fileobj:
print(res.fileobj)
except EOFError:
return
finally:
readline.write_history_file(HISTORY)
示例7: 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()
示例8: postloop
def postloop(self):
self._msgbody_save([])
try:
readline.write_history_file(HISTORY_FILE)
except IOError, e:
# Assume can't write and forget about it
pass
示例9: main
def main():
parser = argparse.ArgumentParser(description='King Phisher Interactive Database Console', conflict_handler='resolve')
utilities.argp_add_args(parser)
config_group = parser.add_mutually_exclusive_group(required=True)
config_group.add_argument('-c', '--config', dest='server_config', help='the server configuration file')
config_group.add_argument('-u', '--url', dest='database_url', help='the database connection url')
arguments = parser.parse_args()
if arguments.database_url:
database_connection_url = arguments.database_url
elif arguments.server_config:
server_config = configuration.ex_load_config(arguments.server_config)
database_connection_url = server_config.get('server.database')
else:
raise RuntimeError('no database connection was specified')
engine = manager.init_database(database_connection_url)
session = manager.Session()
rpc_session = aaa.AuthenticatedSession(user=getpass.getuser())
console = code.InteractiveConsole(dict(
engine=engine,
graphql_query=graphql_query,
manager=manager,
models=models,
pprint=pprint.pprint,
rpc_session=rpc_session,
session=session
))
console.interact('starting interactive database console')
if os.path.isdir(os.path.dirname(history_file)):
readline.write_history_file(history_file)
示例10: _cli_loop
def _cli_loop(self):
'''
Starts the configuration shell interactive loop, that:
- Goes to the last current path
- Displays the prompt
- Waits for user input
- Runs user command
'''
while not self._exit:
try:
readline.parse_and_bind("%s: complete" % self.complete_key)
readline.set_completer(self._complete)
cmdline = raw_input(self._get_prompt()).strip()
except EOFError:
self.con.raw_write('exit\n')
cmdline = "exit"
self.run_cmdline(cmdline)
if self._save_history:
try:
readline.write_history_file(self._cmd_history)
except IOError:
self.log.warning(
"Cannot write to command history file %s." \
% self._cmd_history)
self.log.warning(
"Saving command history has been disabled!")
self._save_history = False
示例11: save_history
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'
示例12: start
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")
示例13: save_history
def save_history(new_historyPath=historyPath):
try:
import readline
except ImportError:
print("Import Error in __main__: Module readline not available.")
else:
readline.write_history_file(new_historyPath)
示例14: repl
def repl(prompt='emlisp> ', env=None, inport=None, out=sys.stdout):
if os.path.exists(os.path.expandvars(HISTORY_FILENAME)):
readline.read_history_file(os.path.expandvars(HISTORY_FILENAME))
# if env is None:
# env = environment.standard_environment()
if inport is None:
inport = types.InPort(None, prompt=prompt)
while True:
try:
val = None
x = read(inport)
if x is types.eof_object:
if out:
print >> out, '\n'
readline.write_history_file(os.path.expandvars(
HISTORY_FILENAME))
return
val = types.eval(x, env)
if val is not types.nil_object and out:
print >> out, val.display()
except Exception as e:
print '%s: %s' % (type(e).__name__, e)
if '*debug*' in env:
traceback.print_exc()
示例15: interact
def interact(self, cmd=None):
_reset_readline()
if cmd and isinstance(cmd, BaseCommands):
self.push_command(cmd)
if readline:
oc = readline.get_completer()
readline.set_completer(self._rl_completer)
try:
try:
while 1:
ui = self._cmd._ui
try:
line = ui.user_input()
if not line:
continue
while self.feed(line+"\n"):
line = ui.more_user_input()
except EOFError:
self._cmd._print()
self.pop_command()
except (CommandQuit, CommandExit): # last command does this
pass
finally:
if readline:
readline.set_completer(oc)
if self._historyfile:
try:
readline.write_history_file(self._historyfile)
except:
pass