在用户使用input()输入文本后从控制台删除提示

2024-10-02 04:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以删除用户在使用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模块,但是它隐藏了用户输入的内容,因为它是为密码设计的。我查看了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

它还允许用户使用backspace键删除提示。你知道吗

第三次尝试

我知道我可以使用os.system("cls")清除控制台中的所有内容,但这会删除以前控制台中的文本。例如,此代码:

import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)

删除输入之前打印到控制台的foo。如果我的问题不能直接解决,是否有一种解决方法可以将控制台中的文本保存为变量,然后在用户输入后清除控制台并重新打印控制台中的文本?你知道吗


Tags: 代码text用户文本youhelloinputsome
1条回答
网友
1楼 · 发布于 2024-10-02 04:31:04

这绝对不是最佳解决方案; 然而,针对

is there a workaround that can save the text in the console to a variable

,您可以继续将所需的文本附加到变量,并按照建议每次重新打印该文本。再说一次,我不建议将此作为您的实际实现,但是当我们等待有人提供正确的方法时。。。你知道吗

import os

to_print = ""
to_print += "foo" + "\n"
print(to_print)

user_input = input("Enter some text: ")
os.system("cls")

to_print += "You just entered " + user_input + "\n"
print(to_print)

相关问题 更多 >

    热门问题