如何在 python raw_input 中使用 tab 键补全?
ringa_lee
ringa_lee 2017-04-18 09:16:38
[Python讨论组]

如何在 python raw_input 中使用 tab 键补全?

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
黄舟

拋磚

用 readline, 以下是一個簡單的小範例:

import readline

CMD = ['foo1', 'foo2', 'bar1', 'bar2', 'exit']

def completer(text, state):
    options = [cmd for cmd in CMD if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind("tab: complete")
readline.set_completer(completer)

while True:
    cmd = raw_input('==> ')
    if cmd=='exit':
        break
    print(cmd)

測試:

==> <TAB><TAB>
bar1  bar2  exit  foo1  foo2
==> b<TAB>
==> bar
==> bar<TAB><TAB>
bar1  bar2  
==> bar1
bar1
==> exit

  • python - readline

  • GNU Readline Library


引玉

其實我沒有完全理解 completer 的作用原理, 尤其是 state 的部分, 希望有高手可以闡釋, 十分感謝!


我回答過的問題: Python-QA

伊谢尔伦

http://stackoverflow.com/ques...
这段代码写得不错,如果要补全第二个参数要自己写 complete 函数类似于下面的代码。

    def complete_cd(self, *args):
        cwd = CURRENT_PATH
        results = [c for c in os.listdir(cwd) if c.startswith(args[0][0])]
        return results

ps:官方文档有说:

    Note The underlying Readline library API may be implemented by the libedit library instead of GNU readline. On MacOS X the readline module detects which library is being used at run time.
    The configuration file for libedit is different from that of GNU readline. If you programmatically load configuration strings you can check for the text “libedit” in readline.__doc__ to differentiate between GNU readline and libedit.

所以在 MAC 和 Windows 上面不适用

如果要在全平台使用(没有测试 Windows),使用如下加载代码

try:
    import readline
except ImportError:
    try:
        import pyreadline as readline
        # throw open a browser if we fail both readline and pyreadline
    except ImportError:
        import webbrowser
        webbrowser.open("http://ipython.scipy.org/moin/PyReadline/Intro#line-36")
        # throw open a browser
    #pass
else:
    import rlcompleter
    if(sys.platform == 'darwin'):
        readline.parse_and_bind ("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号