簡體   English   中英

TAB 鍵在 python 自動完成中不起作用

[英]TAB key not working in python auto-complete

我正在嘗試使用 python 中的 readline 創建一個交互式命令行程序。

文件 run.py 包含以下代碼:

import readline

class SimpleCompleter(object):
    
    def __init__(self, options):
        self.options = sorted(options)
        return

    def complete(self, text, state):
        response = None
        if state == 0:
            # This is the first time for this text, so build a match list.
            if text:
                self.matches = [s for s in self.options if s and s.startswith(text)]
            else:
                self.matches = self.options[:]
                
        try:
            response = self.matches[state]
        except IndexError:
            response = None
        
        return response

def input_loop():
    line = ''
    while line != 'stop':
        line = input('Prompt ("stop" to quit): ')
        print(f'Dispatch {line}')

# Register our completer function
completer = SimpleCompleter(['start', 'stop', 'list', 'print'])
readline.set_completer(completer.complete)

# Use the tab key for completion
readline.parse_and_bind('tab: complete')

# Prompt the user for text
input_loop()

問題是當我嘗試直接從終端運行文件(即python run.py )時,TAB 鍵不被視為自動完成鍵,而是被視為 4 個空格,所以當我按下 TAB 時我沒有得到任何建議鍵兩次; 但是,如果我從 python 控制台(即import run.py )導入文件,則 TAB 鍵被視為自動完成鍵,我得到了預期的建議。

看來問題出在一線

readline.parse_and_bind('tab: complete')

所以我嘗試將它放在一個單獨的配置文件中,如此處所述,但問題仍然存在。

所以問題是為什么會發生這種情況? 以及我該如何解決。

終於找到答案了,問題是我用的是Mac,所以不是

readline.parse_and_bind('tab: complete')

我必須使用

readline.parse_and_bind('bind ^I rl_complete')

現在直接使用python run.py運行代碼,我得到了預期的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM