如何从控制台删除消息?

时间:2019-01-18 13:17:46

标签: python

我想删除键入后要在控制台中显示的文本,我需要将其删除

niz = input("Insert word:")

,因此它将在控制台中说:“插入单词:(他们插入的单词)” 因此,在他们输入单词后,在控制台中将其删除

4 个答案:

答案 0 :(得分:1)

如果您使用的是 Windows ,则可以使用:

import os  
user_input = input("Insert word")   
os.system('cls')  

或者,如果您使用的是 Linux / OS X

import os  
user_input = input("Insert word")
os.system('clear')  

答案 1 :(得分:1)

通常,您对最终用户的终端没有完全控制权-您的程序只是将文本发送到标准输出,并且一旦将其打印出来,它就在用户操作系统或终端仿真器的控制下,因此您无法取回。尽管有三种可能的方法可能与您要尝试的操作相对应。

第一个选择是简单地清除屏幕。从技术上讲,这不会“删除”他们输入的内容,因为他们仍然可以向上滚动并查看文本,但是至少它将不再在屏幕上立即可见。

import os
os.system('cls')
os.system('clear')

第二个选项是将其视为密码字段。这样可以完全避免回显文本,因此,当此人开始键入内容时,屏幕上什么也没有出现,但是您仍然会收到输入。

import getpass
mystring = getpass.getpass()

您可以使用getpass.getpass(prompt="Input: ")更改默认提示(Password:)。

最后,如果这两种方法都不适合您,我建议您使用curses模块。这是一个更复杂的过程,但是它将完全实现您想要执行的操作。下面的代码仅显示一个字符串,然后在用户按Enter时将擦除该字符串,然后在再次按Enter时将结束程序。请查看curses Python manual page,以获取有关如何使用curses的更多详细信息。

import curses

# initialize a curses window
stdscr = curses.initscr()
curses.noecho()
stdscr.keypad(True)

win = curses.newwin(5, 40, 0, 0) # create window at top-left of terminal with height 5 and width 40
win.refresh()
mystring = "hello, world"
win.addstr(mystring) # print a string to the window
win.refresh()
win.getkey() # wait for user input
curpos = curses.getsyx() # get current cursor position
win.move(curpos[0], curpos[1]-len(mystring)) # move the cursor to the beginning of the string
win.refresh()
win.clrtoeol() # erase text from cursor to end of line
win.refresh()
win.getkey() # wait for user input

# close the curses window and return terminal to normal functionality
stdscr.keypad(False)
curses.echo()
curses.endwin()

答案 2 :(得分:0)

您可以通过终端代码进行操作。 对于Windows,您可以

clear = lambda:os.system('cls')

对于Linux,您可以这么做

clear = lambda:os.system('clear')

您只需要调用clear()

答案 3 :(得分:0)

您可以使用诸如getpass之类的无回声输入功能来消除删除用户输入的需要:

import getpass

niz = getpass.getpass(prompt="Insert word:")

print(f'You entered: {niz}')

输出:

Insert word:
You entered: secret