python - 在程序需要在 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
解决方案
您可以做的一件事是将标准输入从您的程序中重定向出去——这不会阻止用户在他们的键盘上打字,但它确实会阻止您的程序注意它。它是这样工作的:
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
当您不希望用户输入影响程序时,您需要关闭它,然后在需要用户输入时重新打开它。
推荐阅读
- java - spring boot和thymeleaf验证失败后如何保留下拉输入值
- visual-studio-code - VSCode 不尊重文件关联
- typescript - 如何将我的 API 函数导入另一个 Typescript 文件?
- postgresql - pg_dump 使 PostgreSQL 服务器崩溃
- amazon-web-services - AWS CDK (.NET) 无法创建临时网关附件
- database-migration - 棱柱迁移是不好的状态
- swift - 在 Swift 中,Objective-C BOOL 被推断为 `()` 而不是 Bool
- python - NotImplementedError:无法将符号张量 (lstm/strided_slice:0) 转换为 numpy 数组
- python - tkinter 中的纯文本,没有任何标签
- r - 将 grViz 对象转换为 DiagrammeR 对象