Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
除了在Python中尝试之外,错误仍然会发生_Python_Amazon Web Services - Fatal编程技术网

除了在Python中尝试之外,错误仍然会发生

除了在Python中尝试之外,错误仍然会发生,python,amazon-web-services,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

我试图捕捉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

我做错了什么?还有,如果出现故障,如何让脚本再次提示用户输入帐户名?

如注释中所述:将相关代码放入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.")

因为那一行不是引发异常的那一行。Python
str
input
永远不会引发
botocore.exceptions.ProfileNotFound
异常。您没有包括所有相关的代码,并且忽略了堆栈跟踪的重要部分。您处理
input()
str()
的异常,而不是
boto3.Session(…)
Session.client(…)
。注意:不要只捕获
之外的所有异常。异常处理不是口袋妖怪的游戏,你不想也不需要捕捉它们。仅捕获可能引发的异常,例如
botocore.ProfileNotFound
input
已返回
str
,无需调用
str
。这就是
输入所做的一切;它没有任何方法或理由来验证您是否输入了有效的AWS帐户。谢谢!成功了。现在我很清楚是什么原因导致了错误以及如何处理它。您可以通过简单地创建一个无限循环(
while True
)并在设置
客户机后添加一个显式的
中断
来摆脱
succeed
变量。