将光标移回以获取输入Python [英] Move the Cursor Back For taking Input Python

查看:504
本文介绍了将光标移回以获取输入Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到以下几点:

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

但是在这里,光标位于:

but here, the cursor is positioned at :

Enter your name:_____________________________________________
                                                             ^
                                                            Here

如何将光标定位在:

Enter your name:_____________________________________________
                ^
               Here

我正在IDLE上执行此操作.(命令提示符也表示赞赏:))

I'm doing this on IDLE. (Command prompt is also appreciated :) )

推荐答案

进一步研究之后,我的最终解决方案是创建自己的自定义输入.注意:这仅适用于Windows命令提示符.如果要在Unix中执行此操作,则必须考虑其他方法.我稍后可能会更新此答案以支持Unix.

Having looked at this further, my final solution is to create my own custom input. NB: this only works in windows command prompt. If you are looking to do this in Unix you will have to look into an alternative. I may update this answer later to support Unix.

同样,这在IDLE中不起作用

此函数为您的输入添加前缀,输入的max_length个数字和blank_char来填充输入的长度.

This function takes a prefix for your input, the number of max_length of the input, and the blank_char to fill the length of the input with.

首先,我们捕获用户输入,如果它是可显示的字符,则将其添加到单词中.每次获取新字符时,都会覆盖现有输入行,以保持与单词的当前状态保持最新.

First, we capture the user input and if it is a displayable character, we add it to our word. Every time we get a new character we overwrite the existing input line to keep up to date with the current state of the word.

我们还会寻找 b'\ x08'字符(退格键),以便我们可以从单词中删除最后一个字符,并返回字符以查看用户是否按下Enter键.

We also look for the b'\x08' charater (backspace) so we can remove the last character from our word, and the return charcter to see if our user has pressed Enter.

按下Enter键后,返回单词.

Once enter has been pressed, return the word.

还有一个内置的限制,即用户只能输入与下划线一样多的字符,因为这会导致字母缠绵,您始终可以通过增加下划线或类似的数字来进行修改.

There is also a built in limit, where the user can only input as many characters as there are underscores, as this will cause letters to linger, you can always modify this by incrementing the number of underscores or something similar.

仅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:

Handling both Windows and Unix

WINDOWS and 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()函数顶部添加以下内容:

Handling IDLE

With IDLE, this fails. Thanks Python for giving us this... Anayway, if you want to handle running in IDLE, simply add the following at the top of the get_input() function:

    import sys

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

这将检查您是否正在使用IDLE,只是提示用户正常输入.

This will check if you are using IDLE and just prompt the user for input normally.

更新1:将光标移动到下一个字符位置

更新2:添加了Unix支持

更新2.1:仅原始Windows答案和Windows和Unix答案分开

更新3:处理IDLE

这篇关于将光标移回以获取输入Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆