我正在使用Mac OS X上的默认python解释器,而我是Cmd + K(清除)我之前的命令.我可以使用箭头键逐个浏览它们.但是有一个选项,比如bash shell中的--history选项,它会显示你到目前为止输入的所有命令吗?
Den*_*zov 218
打印整个历史记录的代码(仅供将来参考):
import readline
for i in range(readline.get_current_history_length()):
print readline.get_history_item(i + 1)
Run Code Online (Sandbox Code Playgroud)
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
Run Code Online (Sandbox Code Playgroud)
编辑:注释get_history_item()从1到n编制索引.
Ign*_*ams 59
使用readline.get_current_history_length()获得的长度,并readline.get_history_item()查看每个.
小智 37
使用python 3解释器编写历史记录
~/.python_history
Mar*_*oma 12
如果要将历史记录写入文件:
import readline
readline.write_history_file('python_history.txt')
Run Code Online (Sandbox Code Playgroud)
帮助功能提供:
import readline
readline.write_history_file('python_history.txt')
Run Code Online (Sandbox Code Playgroud)
@Jason-V,这真的很有帮助,谢谢。然后,我找到了这个例子并组成了自己的片段。
#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
readline.read_history_file(python_history)
readline.parse_and_bind("tab: complete")
readline.set_history_length(5000)
atexit.register(readline.write_history_file, python_history)
except IOError:
pass
del os, python_history, readline, atexit
Run Code Online (Sandbox Code Playgroud)
一个简单的函数来获取类似于unix/bash版本的历史记录。
希望对一些新人有帮助。
def ipyhistory(lastn=None):
"""
param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
Also takes -ve sequence for first n history records.
"""
import readline
assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
hlen = readline.get_current_history_length()
is_neg = lastn is not None and lastn < 0
if not is_neg:
flen = len(str(hlen)) if not lastn else len(str(lastn))
for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
else:
flen = len(str(-hlen))
for r in range(1, -lastn + 1):
print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))
Run Code Online (Sandbox Code Playgroud)
片段:使用 Python3 进行测试。如果 python2 有任何问题,请告诉我。样品:
完整历史:
ipyhistory()
最近 10 条历史记录:
ipyhistory(10)
前 10 条历史:
ipyhistory(-10)
希望对小伙伴们有帮助。
| 归档时间: |
|
| 查看次数: |
82550 次 |
| 最近记录: |