我尝试在PyCharm中从控制台读取一个字符(没有按enter键),但是没有用。函数msvcrt.getch()会停止代码,但不会对按键(甚至是enter)做出反应,并且msvcrt.kbhit()始终返回0。例如,此代码不打印任何内容:
import msvcrt
while 1:
if msvcrt.kbhit():
print 'reading'
print 'done'我使用的是Windows7,PyCharm 3.4 (idle中的相同版本)。
怎么啦?有没有其他方法可以只读输入而不回车?
发布于 2018-01-20 23:57:35
这在Run窗口的特殊模式下是可能的。
在Run/Debug Configurations中选中
Emulate terminal in output console设置复选框发布于 2020-05-30 02:35:16
您正在尝试将<Class 'Bytes'>与<Class 'string'>进行比较。
将key转换为string,然后进行比较:
import msvcrt
while True:
if msvcrt.kbhit():
key = str(msvcrt.getch())
if key == "b'w'":
print(key)要在命令行中运行该程序,请转到: edit Configurations > Execution > enable "Emulate terminal in output console"。
发布于 2020-01-11 17:31:41
此代码将修复。所以使用key.lower()
while True:
key = msvcrt.getch()
if key == "b'w'":
print("Pressed: W without lower()")
#It won't work.
if key.lower() == "b'w'":
print("Pressed: W with lower()")
#This one will work.
#I don't know why but key.lower() works.https://stackoverflow.com/questions/30534218
复制相似问题