Linux為Python添加TAB自動(dòng)補(bǔ)全和命令歷史功能
Linux為Python添加TAB自動(dòng)補(bǔ)全和命令歷史功能
為Python添加交互模式下TAB自動(dòng)補(bǔ)全以及命令歷史功能。如何操作呢?下面是學(xué)習(xí)啦小編跟大家分享的是Linux為Python添加TAB自動(dòng)補(bǔ)全和命令歷史功能,歡迎大家來(lái)閱讀學(xué)習(xí)。
Linux為Python添加TAB自動(dòng)補(bǔ)全和命令歷史功能
方法/步驟
Linux Python Tab 自動(dòng)補(bǔ)全方法:
新建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)境變量:
即時(shí)生效,重啟失效:export PYTHONSTARTUP=~/.pystartup
永久生效:echo "export PYTHONSTARTUP=~/.pystartup" >> /etc/profile
驗(yàn)證:
注:默認(rèn)補(bǔ)全是ESC。
readline.parse_and_bind('tab: complete') 這條命令用來(lái)設(shè)定為tab補(bǔ)全。
Windows Python Tab 自動(dòng)補(bǔ)全方法:
a. 安裝python
b. pip install pyreadline
c. 在Python安裝路徑的Lib文件夾下新建一個(gè)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") 這個(gè)路徑可以自定義設(shè)置。
d. 輸入python就自動(dòng)加載tab補(bǔ)全
和linux類似,如果想輸入python就自動(dòng)加載tab補(bǔ)全,在系統(tǒng)屬性中的環(huán)境變量里增加PYTHONSTARTUP變量,值為絕對(duì)路徑的 tab.py,例如:
變量名:PYTHONSTARTUP
變量值:C:\Program Files (x86)\Python2\Lib\tab.py
注:不做這步的話,每次輸入python進(jìn)入交互界面后,需要手動(dòng)import tab
Linux為Python添加TAB自動(dòng)補(bǔ)全和命令歷史功能相關(guān)文章:
2.很實(shí)用的Linux 系統(tǒng)運(yùn)維常用命令