首页 > 解决方案 > 我如何在python中处理客户端错误处理

问题描述

我是新手,这是我的代码:

with open('Accounts.txt') as f:
    account_list = f.readlines()
    for account in account_list:
        while account_list:
            try:
                account = account.rstrip('\n') #strip end of account in accounts.txt
                assume_response = sts_default_role.assume_role(
                RoleArn = f'arn:aws:iam::{account}:role/user/user.infosec',
                RoleSessionName = 'test_session',
                )
                print(f"Logged in to {account}"),
                print("test first short loop")
                break
            except ClientError:
                print(f"Couldn't login to {account}"),
                break
                assume_creds = assume_response['Credentials']
                session = boto3.session.Session(
                aws_access_key_id=assume_creds['AccessKeyId'],
                aws_secret_access_key=assume_creds['SecretAccessKey'],
                aws_session_token=assume_creds['SessionToken'],
                )
        print("test outside the loop")

这是我的输出:

Logged in to 733443824660
test first short loop
test outside the loop
Couldn't login to 111111222211
test outside the loop

如您所见,它工作得很好,我唯一的问题是,一旦遇到无法登录帐户的异常,我不希望代码走得更远,因为走得更远没有意义当您无法登录帐户时打印(在循环外测试)评论。

有什么想法吗?

标签: python

解决方案


如果您想在无法登录帐户时中断该程序的执行,那么最好退出:

import sys
sys.exit()

此命令将从您的 python 脚本中退出。

break命令只会中断内部循环的执行。要打破外循环,您将不得不再次使用break命令。

但是,如果您无法从列表中登录一个帐户,也许您将能够登录到其他任何一个帐户。


推荐阅读