我刚刚开始使用 Python 的 keyboard
模块。我一直在探索下面的代码,直到第 5 行末尾出现错误。下面的代码的目标是检测我是否按下了键盘上的“a”。我尝试在 print 函数末尾添加分号,并尝试将 print("A")
替换为 pass
和 break
但 Python 给了我和以前一样的错误。
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
输出:
File "c:\users\emma\mu_code\keyboard.py", line 6
Syntax Error: unexpected EOF while parsing
为什么会出现此语法错误以及如何消除它?
最佳答案
在您的代码中添加 except block ,如下所示:
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
except:
#do something else, if there is an error, or any other key is pressed
如果你不知道是否需要 try except,那么就不要将其保留在 try block 中:
import keyboard
while True:
if keyboard.is_pressed('a'):
print("A")
关于python - 解析 Python 中的语法错误时出现意外的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67979593/