我正在Mac OS X上的默认python解释器上工作,我Cmd+K(清除)我之前的命令。我可以用方向键逐个浏览它们。但是bash shell中是否存在类似——history选项的选项,可以显示到目前为止输入的所有命令?
当前回答
使用readline.get_current_history_length()获取长度,并使用readline.get_history_item()查看每个长度。
其他回答
这应该会让你在单独的行中打印出命令:
import readline
map(lambda p:print(readline.get_history_item(p)),
map(lambda p:p, range(readline.get_current_history_length()))
)
使用python3解释器,历史记录被写入 ~ / .python_history
@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
在IPython中,%history -g应该提供整个命令历史。
默认配置还将历史记录保存到用户目录中名为.python_history的文件中。
重新讨论一下Doogle的答案,它不打印行数,但允许指定要打印的行数。
def history(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:
for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
print(readline.get_history_item(r))
else:
for r in range(1, -lastn + 1):
print(readline.get_history_item(r))
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if