解析 Python 中的语法错误时出现意外的 EOF
Unexpected EOF while parsing Syntax Error in Python
我刚开始使用 Python 的 keyboard
模块。我一直在探索下面的代码,直到第 5 行末尾出现错误。下面代码的目的是检测我是否按下了键盘上的“a”。我试图在 print 函数的末尾放一个分号,我试图用 pass
和 break
替换 print("A")
但是 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 块,如下所示:
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 块中:
import keyboard
while True:
if keyboard.is_pressed('a'):
print("A")
你没有添加 except 部分。
如果您使用 try/except 语句,则需要一个 except 语句。
成功了。
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
else:
# Rest code . If you don't want to do anything then simply pass
pass
我刚开始使用 Python 的 keyboard
模块。我一直在探索下面的代码,直到第 5 行末尾出现错误。下面代码的目的是检测我是否按下了键盘上的“a”。我试图在 print 函数的末尾放一个分号,我试图用 pass
和 break
替换 print("A")
但是 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 块,如下所示:
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 块中:
import keyboard
while True:
if keyboard.is_pressed('a'):
print("A")
你没有添加 except 部分。 如果您使用 try/except 语句,则需要一个 except 语句。
成功了。
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
else:
# Rest code . If you don't want to do anything then simply pass
pass