本文整理汇总了Python中readline.write_history_file函数的典型用法代码示例。如果您正苦于以下问题:Python write_history_file函数的具体用法?Python write_history_file怎么用?Python write_history_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_history_file函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:kyrus,项目名称:PyMyo,代码行数:7,代码来源:pyMyoCli.py
示例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'))
开发者ID:b10m,项目名称:func-shell,代码行数:30,代码来源:fsh.py
示例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
开发者ID:dimitri,项目名称:skytools-dev,代码行数:27,代码来源:qadmin.py
示例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
开发者ID:jhunkeler,项目名称:pyraf,代码行数:27,代码来源:pycmdline.py
示例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) )
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:33,代码来源:__init__.py
示例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)
开发者ID:JoM-Lab,项目名称:JoM,代码行数:27,代码来源:repl.py
示例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()
开发者ID:Michael-F-Ellis,项目名称:TransLily,代码行数:60,代码来源:rl_interface.py
示例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
开发者ID:09beeihaq,项目名称:Coursera-SDN-Assignments,代码行数:7,代码来源:simple.py
示例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)
开发者ID:fo0nikens,项目名称:king-phisher,代码行数:32,代码来源:database_console.py
示例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
开发者ID:JonnyJD,项目名称:configshell,代码行数:27,代码来源:shell.py
示例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'
开发者ID:kalanand,项目名称:VPlusJets,代码行数:7,代码来源:pyroot_logon.py
示例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")
开发者ID:YggdrasiI,项目名称:PBStats,代码行数:32,代码来源:Civ4Shell.py
示例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)
开发者ID:Ulm-IQO,项目名称:qudi,代码行数:7,代码来源:__main__.py
示例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()
开发者ID:rpedde,项目名称:emlisp,代码行数:31,代码来源:parser.py
示例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
开发者ID:kdart,项目名称:pycopia3,代码行数:30,代码来源:CLI.py
示例16: getInput
def getInput(prompt, default=None, options=None, password=False):
'''
'''
readline.write_history_file(historyFile)
readline.clear_history()
try:
width = 45
suggestion = ''
if default:
suggestion = '[{:s}]'.format(default)
width-= len(suggestion)
elif options:
suggestion = '{' + '|'.join(options) + '}'
width-= len(suggestion)
formatString = '''{:<''' + str(width) + '''s}{:s}: '''
fullPrompt = formatString.format(prompt, suggestion)
userInput = (raw_input(fullPrompt).lower().strip() if not password
else getpass(fullPrompt))
readline.clear_history()
while (options) and (userInput not in options):
putMessage("Invalid option!",level = severity.ERROR)
userInput = (raw_input(fullPrompt).lower().strip() if not password
else getpass(fullPrompt))
readline.clear_history()
readline.read_history_file(historyFile)
userInput = userInput if userInput else None
return userInput
except KeyboardInterrupt:
readline.read_history_file(historyFile)
raise
开发者ID:MakeICT,项目名称:electronic-door,代码行数:31,代码来源:cli_helper.py
示例17: quits
def quits(showlogo=True):
""" Exit the program. """
if has_readline:
readline.write_history_file(g.READLINE_FILE)
util.dbg("Saved history file")
cache.save()
screen.clear()
msg = logo(c.r, version=__version__) if showlogo else ""
msg += util.F("exitmsg", 2)
if config.CHECKUPDATE.get and showlogo:
try:
url = "https://raw.githubusercontent.com/mps-youtube/mps-youtube/master/VERSION"
v = urlopen(url, timeout=1).read().decode()
v = re.search(r"^version\s*([\d\.]+)\s*$", v, re.MULTILINE)
if v:
v = v.group(1)
if v > __version__:
msg += "\n\nA newer version is available (%s)\n" % v
except (URLError, HTTPError, socket.timeout):
util.dbg("check update timed out")
screen.msgexit(msg)
开发者ID:Ofloo,项目名称:mps-youtube,代码行数:29,代码来源:misc.py
示例18: exit
def exit(self):
"""CLI command to exit the debugger."""
if os.path.isdir(self.confdir):
readline.write_history_file(self.histfile)
sys.exit(0)
开发者ID:da4089,项目名称:monjon,代码行数:7,代码来源:cli.py
示例19: save_history
def save_history(historyPath=historyPath):
try:
import readline
except ImportError:
print "Module readline not available."
else:
readline.write_history_file(historyPath)
开发者ID:lgray,项目名称:usercode,代码行数:7,代码来源:interactiveStackTree.py
示例20: prompt
def prompt(jep):
try:
line = None
while True:
ran = True
try:
ran = jep.eval(line)
except Exception as err:
# if a user uses exit(), don't print the error
if 'exceptions.SystemExit' not in str(err.message):
traceback.print_exc()
try:
if ran:
line = raw_input(PS1)
else:
line = raw_input(PS2)
except:
break
finally:
if has_readline:
try:
readline.write_history_file(history_file)
except IOError:
pass
开发者ID:bsteffensmeier,项目名称:jep,代码行数:26,代码来源:console.py
注:本文中的readline.write_history_file函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论