简体   繁体   English

如何在同一行输入后打印文本

[英]How to print text after input on the same line

I'm wondering if there is a way to be able to print a statement after the input on the same line.我想知道是否有办法在同一行输入后打印语句。

Like how print() has 'end=', but input does not...就像 print() 有 'end=',但输入没有...

user = input("Type Here: ")
print("Text")

# -- Output:
# Type Here: input_here
# text_here

# -- Wanted Output:
# Type Here: input_here text_here

The input() function is not very fancy. input() function 不是很花哨。 And it will advance the cursor down to start of next line when the user hits RETURN.当用户点击 RETURN 时,它会将 cursor 向下推进到下一行的开头。

But you can overwrite what happened on that line by sending an ANSI escape sequence:但是您可以通过发送ANSI转义序列来覆盖该行上发生的事情:

up = chr(27) + "[A"

For example:例如:

name = input("Name? ")
print(up + "Name is " + name + "    Pleased to meet you.    ")

For fancier approaches, you will need a library like curses or GNU readline.对于更高级的方法,您将需要像 curses 或 GNU readline 这样的库。

Go up a line, then forward the length of the input. Go向上一行,然后向前输入的长度。 Note that this doesn't work if there was already text on the current line before calling noline_input请注意,如果在调用noline_input之前当前行上已经有文本,这将不起作用

def noline_input(prompt):
    data = input(prompt)
    print(end=f"\033[F\033[{len(prompt)+len(data)+1}G") # or +2 if you want an extra space
    return data

You can create your own version of the input function by getting keystrokes silently with the msvcrt.getch function in a loop.您可以通过在循环中使用msvcrt.getch function 静默获取击键来创建您自己的input版本 function。 With each keystroke, you either append it to a list and output it to the console, or abort the loop if it's a carriage return.每次击键时,您要么将它 append 到列表,要么将它 output 到控制台,或者如果它是回车则中止循环。

To deal with a backspace, pop the last character from the list and output a backspace, then a space to erase the last character from the console, and then another backspace to actually move the cursor backwards.要处理退格,弹出列表中的最后一个字符和 output 一个退格,然后是一个空格以从控制台中删除最后一个字符,然后另一个退格实际上将 cursor 向后移动。

Note that msvcrt.getch works only in Windows, and you should install the getch package instead in other platforms:请注意, msvcrt.getch仅适用于 Windows,您应该在其他平台上安装getch package:

try:
    from msvcrt import getch
except ModuleNotFoundError:
    from getch import getch

def input_no_newline(prompt=''):
    chars = []
    print(prompt, end='', flush=True)
    while True:
        char = getch().decode()
        if char == '\r':
            break
        if char != '\b':
            chars.append(char)
            print(char, end='', flush=True)
        elif chars:
            chars.pop()
            print('\b \b', end='', flush=True)
    return ''.join(chars)

user = input_no_newline("Type Here: ")
print("Text")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM