5

我正在尝试编写一个非常简单的程序,该程序将等待 x 秒,然后检查是否已按下某个键,然后根据此结果进入代码下方的不同循环。我有这个代码:

import msvcrt
import time
import sys

time.sleep(1)
if msvcrt.kbhit():
    sys.stdout.write('y')
else:
    sys.stdout.write('n')

所以我在它第一次启动时按下任何键(使 kbhit ==true),但它总是落到第二条语句并打印'n'。有什么建议我做错了吗?

{使用 Python 2.7 和 IDLE}

谢谢

4

1 回答 1

10

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

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.

于 2013-09-07T12:33:41.880 回答