如何在 python raw_input 中使用 tab 键补全?
ringa_lee
ringa_lee 2017-04-18 09:16:38
0
2
637

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

ringa_lee
ringa_lee

ringa_lee

membalas semua(2)
黄舟

Membaling batu bata

Gunakan readline, berikut ialah contoh mudah:

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)

Ujian:

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

  • python - readline

  • Perpustakaan Garis Baca GNU


Memperkenalkan jed

Sebenarnya, saya tidak memahami sepenuhnya prinsip kerja pelengkap, terutamanya bahagian state Saya harap seseorang dapat menerangkannya


Soalan yang saya jawab: Python-QA

伊谢尔伦

http://stackoverflow.com/ques...
Kod ini ditulis dengan baik Jika anda ingin melengkapkan parameter kedua, anda mesti menulis fungsi lengkap anda sendiri yang serupa dengan kod berikut.

    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: Dokumen rasmi menyatakan:

    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 上面不适用

Jika anda mahu menggunakannya pada semua platform (Windows tidak diuji), gunakan kod pemuatan berikut

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")
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!