oofer
oofer

Reputation: 27

Python Exception invalid syntax

Python except don't work. I'm trying

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"]

I've tried everything I know. Is there something I need to import or something I'm missing?

Edit: Updated to add more code as requested.

Upvotes: 1

Views: 165

Answers (3)

Manby
Manby

Reputation: 454

I'm assuming that you're trying to read the value in the dictionary parse with key "code", and if there is no such entry, then you wait 2 seconds to try again.

Try this:

print(r.text)
parse = json.loads(r.text)

while True:
    try:
        codeparse = parse["code"]
        break
        
    except KeyError:
        print("Unable to get SMS Code, sleeping for 2 seconds...")
        time.sleep(2)

print("The value is", codeparse)

Upvotes: 1

ForceBru
ForceBru

Reputation: 44858

This is simply invalid syntax: you can't have an except block as part of the while loop:

while not getcode:
    ...
except KeyError:
    pass

Example in the REPL:

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

So, you immediately get a SyntaxError, no matter what's inside the loop.

The proper syntax is:

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

Upvotes: 1

This is how the try except method works... Try some statement(s) and if it raises some error, then the except block will be run

try:
    print(0/0)
except KeyError:
    print('keyerror')
    '''in this block you can add what will happen if the error 
    raised in the try block raises an KeyError'''
except:
    print('some error occured')

Upvotes: 0

Related Questions