python中使用tab补全

发布时间:2019-09-20 07:31:55编辑:auto阅读(1472)

    要能够使用import tab,最主要的是要有readline模块。默认python2.6虽然没有装tab模块,但是装了readline模块的。如下:

    [root@90-163 robin]# python2.6
    Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import tab
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named tab
    >>> import readline

    >>>

    而python2.7默认tab模块和readline模块都没有安装

    [root@90-163 robin]# python
    Python 2.7.5 (default, Apr 16 2015, 15:21:18)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import tab
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named tab
    >>> import readline
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named readline

    python2.6能够import readline成功的原因是因为有这个模块:/usr/lib64/python2.6/lib-dynload/readline.so (默认安装就有的),python2.7.5不能import readline成功的原因就是没有这个模块。所以将这个模块cp到python2.7的相关目录下既可以了。操作如下:

    [root@90-163 lib-dynload]# cp  /usr/lib64/python2.6/lib-dynload/readline.so /usr/local/lib/python2.7/lib-dynload/
    [root@90-163 lib-dynload]# python
    Python 2.7.5 (default, Apr 16 2015, 15:21:18)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import readline
    >>> 

    然后在/usr/local/lib/python2.7/site-packages 添加一个tab.py文件即可使用import tab,内容如下;

    [root@90-163 site-packages]# pwd
    /usr/local/lib/python2.7/site-packages
    [root@90-163 site-packages]# cat tab.py
    try:
        import readline
    except ImportError:
        print("Module readline not available.")
    else:
        import rlcompleter
        readline.parse_and_bind("tab: complete")

    进行测试:

    >>> import readline
    >>> import tab
    >>> import os
    >>> os.w
    os.wait(     os.wait3(    os.wait4(    os.waitpid(  os.walk(     os.write( 



关键字