舒畅 发表于 2018-8-9 08:09:09

python tab键自动补齐命令

我的博客已迁移到xdoujiang.com请去那边和我交流  
一、基础环境
  
1、角色、ip、版本、内核
  
serverA 10.1.10.117 3.2.0-4-amd64 7.8 python readline rlcompleter
  
python-2.7.3
  

  
二、python tab键自动补齐命令安装
  
1、安装python
  
apt-get -y install python
  

  
2、查看下目前已安装的模块
  
python
  
Python 2.7.3 (default, Mar 13 2014, 11:03:55)
  
on linux2
  
Type "help", "copyright", "credits" or "license" for more information.
  
>>> help('modules')
  
Please wait a moment while I gather a list of all available modules...
  
BaseHTTPServer      array               imaplib             sha
  
Bastion             ast               imghdr            shelve
  
CDROM               asynchat            imp               shlex
  
CGIHTTPServer       asyncore            importlib         shutil
  
Canvas            atexit            imputil             signal
  
ConfigParser      audiodev            inspect             site
  
Cookie            audioop             io                  sitecustomize
  
DLFCN               base64            itertools         smtpd
  
Dialog            bdb               json                smtplib
  
DocXMLRPCServer   binascii            keyword             sndhdr
  
FileDialog          binhex            lib2to3             socket
  
FixTk               bisect            linecache         spwd
  
HTMLParser          bsddb               linuxaudiodev       sqlite3
  
IN                  bz2               locale            sre
  
MimeWriter          cPickle             logging             sre_compile
  
Queue               cProfile            macpath             sre_constants
  
ScrolledText      cStringIO         macurl2path         sre_parse
  
SimpleDialog      calendar            mailbox             ssl
  
SimpleHTTPServer    cgi               mailcap             stat
  
SimpleXMLRPCServercgitb               markupbase          statvfs
  
SocketServer      chunk               marshal             string
  
StringIO            cmath               math                stringold
  
TYPES               cmd               md5               stringprep
  
Tix               code                mhlib               strop
  
Tkconstants         codecs            mimetools         struct
  
Tkdnd               codeop            mimetypes         subprocess
  
Tkinter             collections         mimify            sunau
  
UserDict            colorsys            mmap                sunaudio
  
UserList            commands            modulefinder      symbol
  
UserString          compileall          multifile         symtable
  
_LWPCookieJar       compiler            multiprocessing   sys
  
_MozillaCookieJar   contextlib          mutex               sysconfig
  
__builtin__         cookielib         netrc               syslog
  
__future__          copy                new               tabnanny
  
_abcoll             copy_reg            nis               tarfile
  
_ast                crypt               nntplib             telnetlib
  
_bisect             csv               ntpath            tempfile
  
_bsddb            ctypes            nturl2path          termios
  
_codecs             curses            numbers             test
  
_codecs_cn          datetime            opcode            textwrap
  
_codecs_hk          dbhash            operator            this
  
_codecs_iso2022   dbm               optparse            thread
  
_codecs_jp          debconf             os                  threading
  
_codecs_kr          decimal             os2emxpath          time
  
_codecs_tw          difflib             ossaudiodev         timeit
  
_collections      dircache            parser            tkColorChooser
  
_csv                dis               pdb               tkCommonDialog
  
_ctypes             distutils         pickle            tkFileDialog
  
_ctypes_test      doctest             pickletools         tkFont
  
_curses             dumbdbm             pipes               tkMessageBox
  
_curses_panel       dummy_thread      pkgutil             tkSimpleDialog
  
_elementtree      dummy_threading   platform            toaiff
  
_functools          email               plistlib            token
  
_hashlib            encodings         popen2            tokenize
  
_heapq            errno               poplib            trace
  
_hotshot            exceptions          posix               traceback
  
_io               fcntl               posixfile         ttk
  
_json               filecmp             posixpath         tty
  
_locale             fileinput         pprint            turtle
  
_lsprof             fnmatch             profile             types
  
_multibytecodec   formatter         pstats            unicodedata
  
_multiprocessing    fpectl            pty               unittest
  
_pyio               fpformat            pwd               urllib
  
_random             fractions         py_compile          urllib2
  
_socket             ftplib            pyclbr            urlparse
  
_sqlite3            functools         pydoc               user
  
_sre                future_builtins   pydoc_data          uu
  
_ssl                gc                  pyexpat             uuid
  
_strptime         genericpath         quopri            warnings
  
_struct             getopt            random            wave
  
_symtable         getpass             re                  weakref
  
_sysconfigdata      gettext             readline            webbrowser
  
_sysconfigdata_nd   glob                repr                whichdb
  
_testcapi         grp               resource            wsgiref
  
_threading_local    gzip                rexec               xdrlib
  
_warnings         hashlib             rfc822            xml
  
_weakref            heapq               rlcompleter         xmllib
  
_weakrefset         hmac                robotparser         xmlrpclib
  
abc               hotshot             runpy               xxsubtype
  
aifc                htmlentitydefs      sched               zipfile
  
antigravity         htmllib             select            zipimport
  
anydbm            httplib             sets                zlib
  
argparse            ihooks            sgmllib
  
Enter any module name to get more help.Or, type "modules spam" to search
  
for modules whose descriptions contain the word "spam".
  

  
3、需要用到模块说明rlcompleter readline
  
rlcompleter:
  
The rlcompleter module defines a completion function suitable for the readline
  
module by completing valid Python identifiers and keywords.
  
When this module is imported on a Unix platform with the readline module available
  
an instance of the Completer class is automatically created and its complete() method is set as the readline completer.
  
readline:
  
The readline module defines a number of functions to facilitate completion and reading/writing of
  
history files from the Python interpreter.This module can be used directly or via the rlcompleter module.
  
Settings made usingthis module affect the behaviour of both the interpreter interactive
  
prompt and the prompts offered by the raw_input() and input() built-in functions.
  

  
4、具体脚本
  
cat .pythonrc.py
  
#!/usr/bin/python
  
# -*- coding: utf-8 -*-
  
#--------------------------------------------------
  
#Author:jimmygong
  
#Email:jimmygong@taomee.com
  
#FileName:.pythonrc.py
  
#Function:
  
#Version:1.0
  
#Created:2015-10-12
  
#--------------------------------------------------
  
print "success set"
  
try:
  
    import readline
  
except ImportError:
  
    print "Module readline not available."
  
else:
  
    import rlcompleter
  
    readline.parse_and_bind("tab: complete")
  

  
5、执行后会看到相应success set出现说明OK了
  
python .pythonrc.py
  
success set
  

  
6、将pythonrc.py脚本放到.bashrc
  
echo "export PYTHONSTARTUP=~/.pythonrc.py" >> .bashrc
  

  
7、生效
  
source .bashrc
  

  
三、参考文章
  
https://docs.python.org/2/library/rlcompleter.html
  
https://docs.python.org/2/library/
页: [1]
查看完整版本: python tab键自动补齐命令