Linux為Python添加TAB自動補全和命令歷史功能
Linux為Python添加TAB自動補全和命令歷史功能
為Python添加交互模式下TAB自動補全以及命令歷史功能。如何操作呢?下面是學(xué)習(xí)啦小編跟大家分享的是Linux為Python添加TAB自動補全和命令歷史功能,歡迎大家來閱讀學(xué)習(xí)。
Linux為Python添加TAB自動補全和命令歷史功能
方法/步驟
Linux Python Tab 自動補全方法:
新建Python環(huán)境變量配置文件:
vim ~/.pystartup
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=~/.pystartup" in bash.
import atexit
import os
import readline
import rlcompleter
readline.parse_and_bind('tab: complete')
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
設(shè)置Python環(huán)境變量:
即時生效,重啟失效:export PYTHONSTARTUP=~/.pystartup
永久生效:echo "export PYTHONSTARTUP=~/.pystartup" >> /etc/profile
驗證:
注:默認(rèn)補全是ESC。
readline.parse_and_bind('tab: complete') 這條命令用來設(shè)定為tab補全。
Windows Python Tab 自動補全方法:
a. 安裝python
b. pip install pyreadline
c. 在Python安裝路徑的Lib文件夾下新建一個tab.py
例如:C:\Program Files (x86)\Python2\Lib
用編輯器編輯:
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter.
import atexit
import os
import readline
import rlcompleter
import sys
# Tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join("D:\Tmp\history\", ".pythonhistory")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter
注:
histfile = os.path.join("D:\Tmp\history\", ".pythonhistory") 這個路徑可以自定義設(shè)置。
d. 輸入python就自動加載tab補全
和linux類似,如果想輸入python就自動加載tab補全,在系統(tǒng)屬性中的環(huán)境變量里增加PYTHONSTARTUP變量,值為絕對路徑的 tab.py,例如:
變量名:PYTHONSTARTUP
變量值:C:\Program Files (x86)\Python2\Lib\tab.py
注:不做這步的話,每次輸入python進(jìn)入交互界面后,需要手動import tab
Linux為Python添加TAB自動補全和命令歷史功能相關(guān)文章: