在程序需要python输入之前,如何防止用户使用其键盘?

时间:2018-11-19 06:03:57

标签: python

我对python很陌生,我正在创建一个Question / Answer游戏,程序要求玩家回答,然后玩家可以为其输入。但是,存在一个问题,即允许播放器在程序的任何位置发送随机密钥垃圾邮件,从而弄乱了程序本身。

例如:在程序开始时,玩家可以敲击键盘上的任意键,程序将其视为第一个问题的答案,而不会出现该问题。我的问题是:在玩家需要使用键盘之前,有没有办法阻止/锁定键盘?

这是我的代码:

import time

print("Hello, what is your name?")
time.sleep(1)
print("Don't be shy, I promise I won't bite....")
time.sleep(1)
print("or hack your device")
time.sleep(1)
name = raw_input ("type in your name: ")
time.sleep(2)
print("So, your name is"), name
time.sleep(2)
print("So"), name 
time.sleep(1)
print("tell me about yourself")
time.sleep(1)
print("What is your favorite color")
time.sleep(1)
color = raw_input ("Type in your favorite color: ")
time.sleep(2)
print("Is"), color 
time.sleep(1)
print("your favorite color?")
time.sleep(1)
yes = raw_input ("YAY or NEIN: ")
time.sleep(2)
print("Very well, from what I know your name is"), name + (" Your favorite color is"), color
time.sleep(2)
print("Have a good day"), name

1 个答案:

答案 0 :(得分:1)

您可以做的一件事是将标准输入重定向到程序之外,这不会阻止用户在键盘上键入内容,但会阻止您的程序注意它。它是这样的:

import sys
import os

stdin_backup = sys.stdin         # preserve the usual standard input in a variable
devnull = open(os.devnull, 'w')  # open /dev/null, which is where we pipe input we don't care about to

sys.stdin = devnull              # redirect standard input to devnull
print(...)                       # do a bunch of printing
sys.stdin = stdin_backup         # set standard input to pay attention to the console again
name = raw_input("type in your name: ")  # get input from user
sys.stdin = devnull              # start ignoring standard input again
...

基本上,您希望在不希望用户输入影响程序的时候关闭stdin,然后在需要用户输入时将其重新打开。