【发布时间】:2018-08-01 06:58:07
【问题描述】:
在使用input()时,是否可以去掉提示和用户输入的文字?我在 Windows 10 上使用 cmd,并且更喜欢跨平台工作的解决方案,但我并不介意。
第一次尝试
使用代码:
user_input = input("Enter some text: ")
print("You just entered " + user_input)
产生:
Enter some text: hello
You just entered hello
但我想:
Enter some text: hello
然后:
You just entered hello
第二次尝试
我使用了 getpass 模块,但它隐藏了用户输入的内容,因为它是为密码设计的。我查看了getpass2here 的代码,发现它使用了msvcrt 中的getch() 函数。我尝试使用类似的方法,但没有奏效。这段代码:
import msvcrt
prompt = "Enter some text: "
user_input = ""
print(prompt, end="\r")
current_character = ""
while current_character != "\r":
current_character = msvcrt.getch()
user_input += str(current_character, "utf8")
print(prompt + user_input, end="\r")
print("You entered" + user_input)
产生这个输出:
Enter some text: h e l l o
然后当我按下回车键时:
nter some text: h e l l o
它还允许用户使用退格键删除提示。
第三次尝试
我知道我可以使用os.system("cls") 清除控制台中的所有内容,但这会删除之前控制台中的文本。例如这段代码:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
删除在输入之前打印到控制台的foo。如果我要问的不是直接可能的,是否有一种解决方法可以将控制台中的文本保存到变量中,然后在用户输入后清除控制台并重新打印控制台中的文本?
【问题讨论】:
-
@mij 哪个答案解决了只清除 cmd 输出中的特定行?
标签: python