Skip to content

Python Tab Autocomplete自动补全

Linux Python Tab 自动补全方法

1. 新建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

2. 设置Python环境变量

即时生效,重启失效:export PYTHONSTARTUP=~/.pystartup  
永久生效:echo "export PYTHONSTARTUP=~/.pystartup" >> /etc/profile

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") 这个路径可以自定义设置

 

和linux类似,如果想输入python就自动加载tab补全,在系统属性中的环境变量里增加PYTHONSTARTUP变量,值为绝对路径的 tab.py,

例如:变量名:PYTHONSTARTUP      变量值:C:\Program Files (x86)\Python2\Lib\tab.py

注:不做这步的话,每次输入python进入交互界面后,需要手动import tab

 

 

Published inPython

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注