白日依山尽,黄河入海流。欲穷千里目,更上一层楼。 -- 唐·王之涣

python配置tab自动不全

说明

有时候Centos系统默认安装的python进入交互模式下不能使用tab快捷键功能,这个时候需要自己进行相关配置

tab.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env 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.27为例,把
  • 上面的tab.py 放到 /usr/lib/python2.7/site-packages/ 下面,需要先导入sys,再倒入tab模块
  • 可以把tab.py的内容放到 /root/.pythontab文件中,然后在/root/.bash_profile中添加export PYTHONSTARTUP=~/.pythontab, 这种方式不需要再次导入 tab 模块

测试

1
2
3
4
5
6
7
8
9
10
root@pts/2 $ python 
Python 2.7.5 (default, Sep 15 2016, 22:37:39)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import tab
>>> sys.
sys.__class__( sys.__stdout__ sys.executable sys.path
sys.__delattr__( sys.__str__( sys.exit( sys.path_hooks
sys.__dict__ sys.__subclasshook__( sys.exitfunc( sys.path_importer_cache

附加

PYTHONSTARTUP 官网解释:
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 in this file.

简单来说就是这个文件会在第一次进入交互模式的时候会被执行,所以把tab.py 加入到这个变量设定的文件中就可以达到自动导入tab.py,实现自动补全的功能

公众号: DailyJobOps DailyJobOps
作者

Colin

发布于

2016-09-29

许可协议