[英]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.