Python Windows下的readline自动补全

博客首页 » Python Windows下的readline自动补全

发布于 22 Jun 2014 15:39
标签 blog
Python的readline默认在Windows下是不工作的,通过pip添加pyreadline package,就可以弥补这个问题。

#本来想通过添加以下代码,可以让windows下的python命令行有补全的功能。

import rlcompleter, readline  
readline.parse_and_bind('tab: complete')

可是在Windows Python 2.7下,readline在windows下是无效的。

C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named readline

试图添加readline模块也说明了这一点

C:\>pip install readline
Downloading/unpacking readline
  Downloading readline-6.2.4.1.tar.gz (2.3MB): 2.3MB downloaded
  Running setup.py egg_info for package readline
    error: this module is not meant to work on Windows
    Complete output from command python setup.py egg_info:
    error: this module is not meant to work on Windows

通过添加pyreadline,可以解决这一问题

C:\>pip install pyreadline
Downloading/unpacking pyreadline
  Downloading pyreadline-2.0.zip (108kB): 108kB downloaded
  Running setup.py egg_info for package pyreadline
 
    package init file 'pyreadline\configuration\__init__.py' not found (or not a regular file)
Installing collected packages: pyreadline
  Running setup.py install for pyreadline
    package init file 'pyreadline\configuration\__init__.py' not found (or not a regular file)
 
Successfully installed pyreadline
Cleaning up...

再测试一遍,在输入import re后按tab键,就有提示了。

C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind('tab: complete')
>>>
>>> import re
return    repr(     reload(   reduce(   reversed( readline
>>> import readline
>>> quit()

我是从这个文章里找到参考的,只是在我的2.7.3里,import pyreadline as readline并不好用。反而pyreadline在site-package下生成了一个readline.py。我直接import readline就正常了。
http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7

另外,这个文章还介绍了覆盖complete自动补全路径的方法
http://bbs.chinaunix.net/thread-614952-1-1.html

如何在raw_input输入时自动补全路径名?
 
继承Cmd类,然后覆盖complete函数
def complete(self, text, state):
        """Return the next possible completion for 'text'.
 
        If a command has not been entered, then complete against command list.
        Otherwise try to call complete_<command>; to get list of completions.
        """
        if state == 0:
            import readline
            #重新设置过滤字符串。把/设成分割符。
            readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>;?')
            origline = readline.get_line_buffer()
            line = origline.lstrip()
            stripped = len(origline) - len(line)
            begidx = readline.get_begidx() - stripped
            endidx = readline.get_endidx() - stripped
            if begidx>;0:
 
                cmd, args, foo = self.parseline(line)
                #添加对有‘/’的路径和文件的补全
                if r"/" in text:
                    compfunc = self.path_matches
 
                elif cmd == '':
                    compfunc = self.completedefault
                else:
                    try:
                        compfunc = getattr(self, 'complete_' + cmd)
                    except AttributeError:
                        compfunc = self.completedefault
            else:
                compfunc = self.completenames
            self.completion_matches = compfunc(text, line, begidx, endidx)
        try:
            return self.completion_matches[state]
        except IndexError:
            return None
#再添加path_matches函数来补齐路径
def path_matches(self, text, *ignored):
        import os       
        at = text.rfind('/')
        if at <>; 0:
            path = text[0]
            filist = os.listdir(path)
        else:
            path = ''
            filist = os.listdir('/')
        f = text[at+1:]
        matches = []
        n=len(f)
        for word in filist:
            if word[] == f:
                    matches.append("%s/%s" % (path, word))
        return matches

本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • Python Windows下的readline自动补全

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License