King198
King198

Reputation: 1

How can I prevent an user from using their keyboard until the program needs an input in python?

I am rather new to python and I was creating a Question/Answer game where the program ask the player to answer, and the player can give it an input. However, there is a problem, which allows the player to spam random key at any point of the program, messing up the program itslef.

Eg: right at the beginning of the program, the player can hit any key on the keyboard, and the program regards it as the answer to the first question, without the question ever showing up. My question is: Is there a way for me to block/lock the keyboard until the player needs to use it?

Here is my code:

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

Upvotes: 0

Views: 79

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

One thing you can do is redirect the standard input away from your program - this doesn't prevent the user from typing on their keyboard, but it does prevent your program from paying attention to it. It works like this:

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
...

Basically, you'd want to turn stdin off whenever you don't want user input to affect the program, and then turn it back on when the user's input is needed.

Upvotes: 1

Related Questions