如何在python中处理客户端错误处理

如何在python中处理客户端错误处理,python,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

我是新手,下面是我的一段代码:

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")
以下是我的输出:

登录到733443824660 测试第一个短回路 循环外测试 无法登录到111111 222211 循环外测试 正如你所看到的,它工作得很好,我唯一的问题是,一旦我遇到一个异常,我不能登录到一个帐户,我不想让代码进一步,因为当你不能登录到帐户时,它进一步打印循环外的测试注释是没有意义的


有什么想法吗?

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

import sys
sys.exit()
此命令将从python脚本中退出

break命令将仅中断内部循环的执行。要中断外部循环,必须再次使用break命令


但是,如果您无法登录列表中的一个帐户,您可能可以登录到其他任何帐户。

可以建议删除第二个循环以循环列表中的所有帐户:

with open('Accounts.txt') as f:
    account_list = f.readlines()
    for account in 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")
            continue # to go to the next round of the loop
        except ClientError:
            print(f"Couldn't login to {account}"),
            break
            # this block will be not executed
        print("test outside the loop") # will not be called if exception occurs

这回答了你的问题吗?使用exit从程序中断感谢Anastasiia,但是:当我添加sys.exit时,我的输出仍然与我想要的不一样:try:account=account.rstrip'\n'在accounts.txt中剥离account结尾假定\u response=sts\u default\u role.asure\u RoleArn=f'arn:aws:iam:{account}:role/user/user.infosec',RoleSessionName='test_session',PrintFlog进入{account},printtest第一个短循环中断,ClientError除外:printfCouldn不登录{account},sys.exitLogged in to 733447824660 test first short loop无法登录到111111 22211如果我无法登录到帐户,您是对的我想继续尝试登录到下一个帐户登录到733447824660 test first short loop无法登录到111111 22211不确定这是我们想要的。不幸的是,我不知道如何修复你的代码,而不知道它应该做什么和如何工作。如果我的答案不适用于您,并且您希望获得更多帮助,请指定您的代码应该如何工作。