2005-04-10

控制台下,python的自动完成功能

继承unix like系统的优良传统,python也拥有强劲的readline模块(只在UNIX类系统中才能使用),可以很轻松的实现自动完成的功能。下面是我的一些设置:
0$ env | grep python
PYTHONSTARTUP=/home/xyb/.pythonstartup.py
PYTHONPATH=/home/xyb/.python:/home/xyb/py:./
0$ cat ~/.pythonstartup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last modified: 2004年11月11日 星期四 10时50分39秒 [xyb]

import sys
import LazyPython
sys.excepthook = LazyPython.LazyPython()
del sys, LazyPython

# 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=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

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


首先,要有PYTHONSTARTUP环境变量,它会帮助python找到启动时要自动运行的脚本。如果你和我一样使用bash,可以把它直接放到bash的启动脚本.bashrc中:
export PYTHONSTARTUP=~/.pythonstartup.py


其次,要把readline的相关功能放到python启动脚本中,上面的脚本中readline.parse_and_bind('tab: complete')这一句就就是做的这个工作。另外,脚本还加载了其它一些有用的功能,大家可以自己查资料。这个启动脚本也可以从这里下载,请大家按照自己的需要进行修改。

有了这些设置,我们就可以按Tab键来让readline帮我们自动完成了。如果连按两次Tab键,则会把所有匹配的自动列出来:
0$ python
Python 2.3.5 (#2, Mar 26 2005, 17:32:32)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Lazy Python. Type "help LazyPython" for help.
>>> import types
>>> types.
types.BooleanType types.ObjectType
types.BufferType types.SliceType
types.BuiltinFunctionType types.StringType
types.BuiltinMethodType types.StringTypes
types.ClassType types.TracebackType
types.CodeType types.TupleType
types.ComplexType types.TypeType
types.DictProxyType types.UnboundMethodType
types.DictType types.UnicodeType
types.DictionaryType types.XRangeType
types.EllipsisType types.__class__
types.FileType types.__delattr__
types.FloatType types.__dict__
types.FrameType types.__doc__
types.FunctionType types.__file__
types.GeneratorType types.__getattribute__
types.InstanceType types.__hash__
types.IntType types.__init__
types.LambdaType types.__name__
types.ListType types.__new__
types.LongType types.__reduce__
types.MethodType types.__reduce_ex__
types.ModuleType types.__repr__
types.NoneType types.__setattr__
types.NotImplementedType types.__str__
>>> types.F
types.FileType types.FrameType
types.FloatType types.FunctionType
>>> types.F

没有评论: