为python命令行添加Tab键自动补全功能

在使用linux命令的时候我们习惯使用下Tab键,在python下我们也可以实现类似的功能。具体代码如下:

$ cat  startup.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

查看python默认的模块存放路径。拷贝功能脚本到默认模块存放路径: cp startup.py /usr/lib64/python2.x/

这时候可以通过以下方法进行测试:

>>> import os
>>> os.<Tab>

发表回复

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