給python交互式命令行增加自動補全和命令歷史


考完試了,開始研究《python高級編程》

用過zsh的同學肯定對其自動補全功能印象深刻,通過簡單的定制python交互式命令行也能實現類似功能,具體操作如下:

  • 在用戶目錄下新建".pythonstartup"文件,寫入以下內容:
# python startup file
import readline
import rlcompleter
import atexit
import os
#tab completion
readline.parse_and_bind('tab: complete')
#history file
historyfile = os.path.join(os.environ['HOME'],'.pythonstartup')
try:
    readline.read_history_file(historyfile)
except:
    pass
atexit.register(readline.write_history_file,historyfile)
del os,historyfile,readline,rlcompleter

 

  • 增加環境變量,編輯.bashrc或.zshrc文件(根據你的shell確定),加入以下內容:
export PYTHONSTARTUP="/home/ma6174/.pythonstartup"

 

  • 從新打開終端,進入python交互式命令行界面試一下。下面是我的運行效果截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM