Linux为Python添加TAB自动补全和命令历史功能
为Python添加交互模式下TAB自动补全以及命令历史功能。如何操作呢?下面是学习啦小编跟大家分享的是Linux为Python添加TAB自动补全和命令历史功能,欢迎大家来阅读学习。
Linux为Python添加TAB自动补全和命令历史功能
方法/步骤
Linux Python Tab 自动补全方法:
新建Python环境变量配置文件:
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
设置Python环境变量:
即时生效,重启失效:export PYTHONSTARTUP=~/.pystartup
永久生效:echo "export PYTHONSTARTUP=~/.pystartup" >> /etc/profile
验证:
注:默认补全是ESC。
readline.parse_and_bind('tab: complete') 这条命令用来设定为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") 这个路径可以自定义设置。
d. 输入python就自动加载tab补全
和linux类似,如果想输入python就自动加载tab补全,在系统属性中的环境变量里增加PYTHONSTARTUP变量,值为绝对路径的 tab.py,例如:
变量名:PYTHONSTARTUP
变量值:C:\Program Files (x86)\Python2\Lib\tab.py
注:不做这步的话,每次输入python进入交互界面后,需要手动import tab
Linux为Python添加TAB自动补全和命令历史功能相关文章: