python~实现tab补全

时间:2023-03-08 17:54:11

文章摘自:http://www.jb51.net/article/58009.htm

第一、如在在vim下实现代码的补全功能。

想要为vim实现自动补全功能,则要下载插件

cd /usr/local/src

wget https://github.com/rkulla/pydiction/archive/master.zip

unzip -q master

mkdir -p ~/.vim/tools/pydiction

cp -r pydiction/after ~/.vim

cp pydiction/complete-dict ~/.vim/tools/pydiction

确保文件的结构如下:

[root@git src]# tree ~/.vim
/root/.vim
├── after
│   └── ftplugin
│       └── python_pydiction.vim
└── tools
    └── pydiction
        └── complete-dict

创建~/.vimrc,确保其中内容如下:

filetype plugin on
let g:pydiction_location = '~/.vim/tools/pydiction/complete-dict'

现在我们就可以实现在vim环境下代码补全功能了。

第二、在交互模式下怎么实现Tab补全功能

首先我们找到python 默认的模块的存放路径:

>>> import sys

>>> sys.path
['', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages']

[root@git ~]# cd /usr/local/lib/python2.7/site-packages/

[root@git site-packages]# cat tab.py
#!/usr/bin/python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

vim  .bashrc

添加如下内容

#for python tab
export PYTHONSTARTUP=/usr/local/lib/python2.7/site-packages/tab.py

这样在python的交互模式下也可以是实现Tab补全功能了。