首页 > 解决方案 > 在程序需要在 python 中输入之前,如何防止用户使用他们的键盘?

问题描述

我对python相当陌生,我正在创建一个问题/答案游戏,程序要求玩家回答,玩家可以给它一个输入。但是,存在一个问题,它允许玩家在程序的任何位置发送随机密钥,从而弄乱程序本身。

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

这是我的代码:

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

标签: python

解决方案


您可以做的一件事是将标准输入从您的程序中重定向出去——这不会阻止用户在他们的键盘上打字,但它确实会阻止您的程序注意它。它是这样工作的:

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当您不希望用户输入影响程序时,您需要关闭它,然后在需要用户输入时重新打开它。


推荐阅读