首页 > 解决方案 > Python 异常无效语法

问题描述

Pythonexcept不工作。我正在努力

r = requests.get('URL') # URL returns something like: {"code": ["12345678"]} 
print(r.text)
parse = json.loads(r.text)

getcode = False
while not getcode:
    time.sleep(2)
    codeparse = parse["code"]
    print("Unable to get SMS Code, sleeping for 2 seconds...")
except KeyError:
    pass

getcode = parse["code"]

我已经尝试了我所知道的一切。有什么我需要导入或缺少的东西吗?

编辑:更新以根据要求添加更多代码。

标签: python

解决方案


这只是无效的语法:您不能将except块作为while循环的一部分:

while not getcode:
    ...
except KeyError:
    pass

REPL 中的示例:

>>> while 1:
...  print("g")
... except KeyError:
  File "<stdin>", line 3
    except KeyError:
    ^
SyntaxError: invalid syntax
>>>

SyntaxError因此,无论循环内有什么,您都会立即得到一个。

正确的语法是:

try:
   # some code
   ...
except KeyError:
   ...

推荐阅读