尝试在Python中除外,但错误仍然发生

时间:2019-04-06 21:48:39

标签: python amazon-web-services

我正在尝试在python中捕获错误,当有人输入一个AWS账户名称时,该账户在系统上没有配置文件。

try:
    aws_account = str(input("Enter the name of the AWS account you'll be working in: "))
except:
    print("No account exists by that name.")
session = boto3.Session(profile_name=aws_account)
client = session.client('iam')

但是,如果我输入了错误的帐户名,仍然会发生错误:

 raise ProfileNotFound(profile=profile_name)
botocore.exceptions.ProfileNotFound: The config profile (jf-ruby-dev) could not be found

我在做什么错?另外,如果发生故障,如何获取脚本以再次提示用户输入帐户名?

1 个答案:

答案 0 :(得分:1)

就像注释中所述:将相关代码放在try子句中,并引发特定的异常。您可以再次循环提示。像这样:

succeeded = False
while not succeeded:
    try:
        aws_account = input("Enter the name of the AWS account you'll be working in: ")
        session = boto3.Session(profile_name=aws_account)
        client = session.client('iam')    
        succeeded = True
    except botocore.ProfileNotFound:
        print("No account exists by that name.")