问题描述
我正在尝试编写一个非常简单的程序,该程序将等待 x 秒,然后检查是否按下了某个键,然后根据此结果将进入代码下方的不同循环.我有这个代码:
I'm trying to write a very simple program that will wait for x seconds before checking to see it a key has been pressed then, depending on this outcome will go into a different loop further down the code. I have this code:
import msvcrt
import time
import sys
time.sleep(1)
if msvcrt.kbhit():
sys.stdout.write('y')
else:
sys.stdout.write('n')
所以我在第一次启动时按任意键(使 kbhit ==true)但它总是落在第二个语句并打印n".有什么建议我做错了吗?
So I press any key when it first starts (making kbhit ==true) but it always just falls to the second statement and prints 'n'.Any suggestions what I'm doing wrong?
{使用 Python 2.7 和空闲}
{Using Python 2.7 and IDLE}
谢谢
推荐答案
msvcrt.kbhit()
函数只有在它所在的程序已经从 Windows 命令行(或如果当您双击其 .py
文件时为其输入和输出打开了控制台窗口).
The msvcrt.kbhit()
function will only work if the program it is in has been run from the windows command line (or if a console window is opened for its input and output when you double click on its .py
file).
如果您从 IDLE 运行或使用 pythonw.exe
解释器,程序将不会连接到控制台窗口和 console-IO 命令 来自 msvcrt
将不起作用.
If you run from IDLE or using the pythonw.exe
interpreter, the program won't be connected to a console window and the console-IO commands from msvcrt
won't work.
这篇关于Python kbhit() 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!