在Python中获取辅助输入来控制历史记录



我想在Python 2中构建一个"输入历史"脚本。x,但是我在使用raw_input()时遇到了一些麻烦,无法获得辅助输入,并写入用户输入的内容。

因为我发现它有点难以解释,所以我提供了一个javascript + HTML的例子来尝试澄清一些事情。

JavaScript + HTML示例

(代码片段形式)

var input = document.getElementById("input"),
  button = document.getElementById("button"),
  ihistory = document.getElementById("ihistory"),
  history = [],
  position = 0,
  text = "";
button.onclick = function() {
  if (input.value != "") {
    history.push(input.value);
    input.value = "";
    position++;
    input.focus();
  }
};
input.onkeydown = function(e) {
  if (e.keyCode == 38 && position - 1 >= 0) {
    e.preventDefault();
    position--;
    input.value = history[position].toString();
  } else if (e.keyCode == 40 && position + 1 <= history.length) {
    e.preventDefault();
    position++;
    input.value = history[position].toString();
  } else if (e.keyCode == 13) {
    button.click();
  }
}
<input type="text" id="input"></input>
<button id="button">Submit</button>
<br />
<br />
<br />
<hr />
<p>To Submit text to the text to the history, press "submit".</p>
<p>To access previous history, press the up arrow key. To access future history, press the down arrow key.</p>

我不确定是否可以编写用户输入的内容,以便他们可以编辑它,等等,而不编写C/++代码。如果它确实需要C/++,或者如果它需要任何奇怪的(但最好是小的)模块,我就可以接受。此外,我是在Linux环境下编程的,所以我对Windows/mac的答案不感兴趣。

你所描述的是readline功能。这里有一些如何使用它的示例。一旦您了解了这个函数,您可能会发现这个问题已经在SO中得到了解答。

最新更新