I'm working on the default python interpreter on Mac OS X, and I Cmd+K (cleared) my earlier commands. I can go through them one by one using the arrow keys. But is there an option like the --history option in bash shell, which shows you all the commands you've entered so far?
我正在開發Mac OS X上的默認python解釋器,並且我的Cmd+K(清除)了前面的命令。我可以用箭頭鍵逐個檢查。但是,在bash shell中是否有類似的——history選項,它顯示到目前為止您輸入的所有命令?
7 个解决方案
#1
44
使用readlin .get_current_history_length()獲取長度,並使用readlin .get_history_item()查看每個長度。
#2
158
Code for printing the entire history (just for future reference):
打印整個歷史的代碼(僅供以后參考):
python2
import readline
for i in range(readline.get_current_history_length()):
print readline.get_history_item(i + 1)
python3
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
Edit: Note get_history_item() is indexed from 1 to n.
編輯:注意get_history_item()的索引從1到n。
#3
16
With python 3 interpreter the history is written to
~/.python_history
使用python 3解釋器,歷史記錄被寫入~/.python_history
#4
4
Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:
因為上面只適用於python 2。python 3 x。x(具體來說是3.5)是相似的,但是稍微做了修改:
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
note the extra ()
注意額外的()
(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)
(使用shell腳本來解析.python_history或者使用python來修改上面的代碼是我個人的喜好和情況)
#5
1
If you want to write the history to a file:
如果你想把歷史寫進一個文件:
import readline
with open('pyhistory.txt', 'w') as f:
for i in range(readline.get_current_history_length()):
f.write(readline.get_history_item(i + 1) + "\n")
#6
0
@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.
@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
#7
0
This should give you the commands printed out in separate lines:
這將為您提供以不同行打印出來的命令:
import readline
map(lambda p:print(readline.get_history_item(p)),
map(lambda p:p, range(readline.get_current_history_length()))
)