将光标移回以获取输入 Python

Move the Cursor Back For taking Input Python

我正在尝试执行以下操作:

a = input('Enter your name:_____________________________________________')

但是在这里,光标定位在:

Enter your name:_____________________________________________
                                                             ^
                                                            Here

如何将光标定位在:

Enter your name:_____________________________________________
                ^
               Here

我正在空闲状态下执行此操作。 (命令提示符也很受欢迎)

编写文本提示、一些下划线,然后是相同数量的退格字符 (\b)。

n_underscores = 45
a = input('Enter your name:' + '_' * n_underscores + '\b' * n_underscores)
print('Hi,', a)

您可以使用 \r 字符 return 到行首并覆盖文本,直到您需要输入光标:

print("Enter your name: ____________________", end='\rEnter your name: ', flush=True)
a = input()

值得注意的是,移动光标仅在某些控制台下有效,例如,在 IDLE 下无效,但在 windows 命令提示符下有效

进一步研究后,我的最终解决方案是创建我自己的自定义输入。注意:这仅适用于 windows 命令提示符。如果您希望在 Unix 中执行此操作,则必须寻找替代方案。稍后我可能会更新此答案以支持 Unix。 [编辑:更新以支持 Unix 和 Windows]

同样,这在 IDLE 中不起作用

此函数为您的输入取一个前缀,输入的 max_length 个数,以及用来填充输入长度的 blank_char。

首先,我们捕获用户输入,如果它是可显示的字符,我们将其添加到我们的词中。每次我们得到一个新字符时,我们都会覆盖现有的输入行以跟上单词的当前状态。

我们还寻找 b'\x08' 字符(退格键)以便我们可以从我们的单词中删除最后一个字符,以及 return 字符以查看我们的用户是否按下了 Enter。

一旦按下回车键,return 单词。

还有一个内置限制,用户只能输入与下划线一样多的字符,因为这会导致字母逗留,您可以随时通过增加下划线或类似的数量来修改它。

WINDOWS 仅:

import msvcrt


def windows_get_input(prefix="", underscores=20, blank_char='_'):

    word = ""

    print(prefix + (underscores - len(word)) * blank_char, end='\r', flush=True)
    # Reprint prefix to move cursor
    print(prefix, end="", flush=True)

    while True:
        ch = msvcrt.getch()
        if ch in b'\x08':
            # Remove character if backspace
            word = word[:-1]
        elif ch in b'\r':
            # break if enter pressed
            break
        else:
            if len(word) == underscores:
                continue
            try:
                char = str(ch.decode("utf-8"))
            except:
                continue
            word += str(char)
        # Print `\r` to return to start of line and then print prefix, word and underscores.
        print('\r' + prefix + word + (underscores - len(word)) * blank_char, end='\r', flush=True)
        # Reprint prefix and word to move cursor
        print(prefix + word, end="", flush=True)
    print()
    return word

print(windows_get_input("Name: ", 20, '_'))

同时处理 Windows 和 Unix

WINDOWS 和 UNIX:

def unix_getch():
    import termios
    import sys, tty
    def _getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch.encode("utf-8")
    return _getch()

def get_input(prefix="", underscores=20, blank_char='_'):

    word = ""

    try:
        import msvcrt
        func = msvcrt.getch
    except:
        func = unix_getch

    print(prefix + (underscores - len(word)) * blank_char, end='\r', flush=True)
    # Reprint prefix to move cursor
    print(prefix, end="", flush=True)

    while True:
        ch = func()
        if ch in b'\x08\x7f':
            # Remove character if backspace
            word = word[:-1]
        elif ch in b'\r':
            # break if enter pressed
            break
        else:
            if len(word) == underscores:
                continue
            try:
                char = str(ch.decode("utf-8"))
            except:
                continue
            word += str(char)
        # Print `\r` to return to start of line and then print prefix, word and underscores.
        print('\r' + prefix + word + (underscores - len(word)) * blank_char, end='\r', flush=True)
        # Reprint prefix and word to move cursor
        print(prefix + word, end="", flush=True)
    print()
    return word

print(get_input("Name: ", 20, '_'))

处理空闲

对于 IDLE,这会失败。感谢 Python 给我们这个...无论如何,如果你想在 IDLE 中处理 运行,只需在 get_input() 函数的顶部添加以下内容:

    import sys

    if 'idlelib.run' in sys.modules:
        return input(prefix)

这将检查您是否正在使用 IDLE,并仅提示用户正常输入。