2
$\begingroup$

I'm trying to write a code so that if the token exists then it loads the account or else it asks the user for the API token. Below is the code for reference:

from qiskit import IBMQ
try:
    IBMQ.load_account()
except Exception as e:
    api_key = input("Enter IBMQ API Key")
    IBMQ.save_account(api_key, overwrite=True)
    IBMQ.load_account()

However, even after using the exception handling, still getting below errors:

RequestsApiError: '401 Client Error: Unauthorized for url: https://auth.quantum-computing.ibm.com/api/users/loginWithToken. Login failed., Error code: 3446.'
IBMQAccountCredentialsInvalidToken: 'Invalid IBM Quantum Experience token found: "" of type <class \'str\'>.'

Any work around this to resolve this issue?

$\endgroup$
1
  • $\begingroup$ You are not handling the exception for after the token you input is invalid. Enter the valid token and this should work. $\endgroup$ Feb 7 at 22:44
0
$\begingroup$

The way I would do this is slight different:

from qiskit import IBMQ

api_key = None
for attempt in range(3):                                                # <- (1)
    try:                                                                # <- (3)
        if api_key:
            IBMQ.save_account(api_key, overwrite=True)
        else:
            IBMQ.load_account()
        break                                                           # <- (4)
    except Exception:
        api_key = input("Enter IBMQ API Key (attempt %s): " % attempt)  # <- (2)

This 3-time-loop (line (1), you can replace it for while True: if you prefer infinite looping over this) sets a variable api_key (line (2)) continuously asking for the key while something goes wrong (line (3)). The things that can go wrong are save_account and load_account. If nothing goes wrong (line (4)), then get out of the loop.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.