【问题标题】:Python user input replay [duplicate]Python用户输入重播[重复]
【发布时间】:2013-08-24 12:29:24
【问题描述】:

如何获得最后一个 raw_input?我的 py 提出问题(raw_input),如果用户输入错误,则再次询问相同的问题,并且用户需要重新输入,那么我怎样才能获得最后一个输入以使 de 用户只需编辑它??(就像一个外壳按下键)

【问题讨论】:

    标签: python input raw-input replay


    【解决方案1】:

    您正在寻找readline module。这是example from effbot.org

    # File: readline-example-2.py
    
    class Completer:
        def __init__(self, words):
            self.words = words
            self.prefix = None
        def complete(self, prefix, index):
            if prefix != self.prefix:
                # we have a new prefix!
                # find all words that start with this prefix
                self.matching_words = [
                    w for w in self.words if w.startswith(prefix)
                    ]
                self.prefix = prefix
            try:
                return self.matching_words[index]
            except IndexError:
                return None
    
    import readline
    
    # a set of more or less interesting words
    words = "perl", "pyjamas", "python", "pythagoras"
    
    completer = Completer(words)
    
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer.complete)
    
    # try it out!
    while 1:
        print repr(raw_input(">>> "))
    

    【讨论】:

    • 如果您只需要命令历史记录,您实际上并不需要完成程序。导入readline 足以初始化历史功能。
    【解决方案2】:

    使用readline 模块。

    import readline
    
    # Everything magically works now!
    

    如果您想要标签完成和其他好东西,可以使用更复杂的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多