[英]How to print text after input on the same line
我想知道是否有办法在同一行输入后打印语句。
就像 print() 有 'end=',但输入没有...
user = input("Type Here: ")
print("Text")
# -- Output:
# Type Here: input_here
# text_here
# -- Wanted Output:
# Type Here: input_here text_here
input()
function 不是很花哨。 当用户点击 RETURN 时,它会将 cursor 向下推进到下一行的开头。
但是您可以通过发送ANSI转义序列来覆盖该行上发生的事情:
up = chr(27) + "[A"
例如:
name = input("Name? ")
print(up + "Name is " + name + " Pleased to meet you. ")
对于更高级的方法,您将需要像 curses 或 GNU readline 这样的库。
Go向上一行,然后向前输入的长度。 请注意,如果在调用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
您可以通过在循环中使用msvcrt.getch
function 静默获取击键来创建您自己的input
版本 function。 每次击键时,您要么将它 append 到列表,要么将它 output 到控制台,或者如果它是回车则中止循环。
要处理退格,弹出列表中的最后一个字符和 output 一个退格,然后是一个空格以从控制台中删除最后一个字符,然后另一个退格实际上将 cursor 向后移动。
请注意, 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.