是否可以删除用户在使用input()
时键入的提示和文本?我在windows10上使用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模块,但是它隐藏了用户输入的内容,因为它是为密码设计的。我查看了getpass2
here的代码,发现它使用了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
它还允许用户使用backspace键删除提示。你知道吗
我知道我可以使用os.system("cls")
清除控制台中的所有内容,但这会删除以前控制台中的文本。例如,此代码:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
删除输入之前打印到控制台的foo
。如果我的问题不能直接解决,是否有一种解决方法可以将控制台中的文本保存为变量,然后在用户输入后清除控制台并重新打印控制台中的文本?你知道吗
这绝对不是最佳解决方案; 然而,针对
,您可以继续将所需的文本附加到变量,并按照建议每次重新打印该文本。再说一次,我不建议将此作为您的实际实现,但是当我们等待有人提供正确的方法时。。。你知道吗
相关问题 更多 >
编程相关推荐