【问题标题】:Avoid control sequences(like ^[[C) from Python standard inputstream避免来自 Python 标准输入流的控制序列(如 ^[[C)
【发布时间】:2021-03-31 11:14:28
【问题描述】:

代码:

s = input("Enter a String : \n")
print("The Entered String is : " + s)
print("The Length of Entered String is : " + str(len(s)))

输出:

┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $python try.py
Enter a String : 
hello
The Entered String is : hello
The Length of Entered String is : 5
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $python try.py
Enter a String : 
hello^[[D
The Entered String is : hello
The Length of Entered String is : 8

当我按箭头键时 ^[[C 出现而不是光标移动(其他箭头键、转义键、home、end 发生类似的事情)!

这里发生的事情是字符串第二次包含字符:

['h', 'e', 'l', 'l', 'o', '\x1b', '[', 'C']

所以,'\x1b', '[', 'C' 是从键盘发送到外壳的字符序列,用于表示右箭头键(向前光标)。

我想要的是这些字符不会显示在外壳中,但光标会移动(根据按下的键向前、向后、到家、结束等)。

输入后处理意义不大,主要目的是让光标移动!

如何在 Python 中实现这一点?

异常

但是如果我们直接使用python解释器就可以了:

这是终端输出:

┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $python
Python 3.9.2 (default, Feb 28 2021, 17:03:44) 
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = input("Enter a String : \n")
Enter a String : 
hello
>>> print("The Entered String is : " + s)
The Entered String is : hello
>>> print("The Length of Entered String is : " + str(len(s)))
The Length of Entered String is : 5
>>> s = input("Enter a String : \n")
Enter a String : 
hello
>>> print("The Entered String is : " + s)
The Entered String is : hello
>>> print("The Length of Entered String is : " + str(len(s)))
The Length of Entered String is : 5

尽管按下箭头键、escape 或 home,但输出是相同的。

[编辑]

唯一的目标是在使用程序时为用户提供与终端一样的体验。

【问题讨论】:

    标签: python shell stdin interpreter


    【解决方案1】:

    input 的文档提到以下内容:

    如果 readline 模块已加载,则 input() 将使用它来提供精细的行编辑和历史记录功能。

    所以,我们使用您的程序,并添加一个import readline,现在我们从中获取光标处理和其他项目:

    import readline
    
    s = None
    
    while s != 'exit':
        s = input("Enter a String : \n")
        print("The Entered String is : '{}'".format(s))
        print("The Length of Entered String is : {}".format(len(s)))
    

    在这种情况下,我可以运行它:

    Enter a String :
    hello world
    The Entered String is : 'hello world'
    The Length of Entered String is : 11
    Enter a String :
    hello   world
    The Entered String is : 'hello   world'
    The Length of Entered String is : 13
    Enter a String :
    exit
    The Entered String is : 'exit'
    The Length of Entered String is : 4
    

    我可以使用向上箭头返回并编辑之前的输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2014-11-22
      • 1970-01-01
      • 2010-12-18
      • 2021-07-05
      相关资源
      最近更新 更多