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
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
如您所见,它工作得很好,我唯一的问题是,一旦遇到无法登录帐户的异常,我不希望代码走得更远,因为走得更远没有意义当您无法登录帐户时打印(在循环外测试)评论。
有什么想法吗?
解决方案
如果您想在无法登录帐户时中断该程序的执行,那么最好退出:
import sys
sys.exit()
此命令将从您的 python 脚本中退出。
break命令只会中断内部循环的执行。要打破外循环,您将不得不再次使用break命令。
但是,如果您无法从列表中登录一个帐户,也许您将能够登录到其他任何一个帐户。
推荐阅读
- php - PHP org.json.JSONException 的 Android 问题:在字符 0 处输入结束
- ios - 检测键盘何时以交互方式关闭
- ios - 解析 JSON 错误“预期解码数组
但找到了一个号码 - xamarin.forms - Xamarin Forms 4.5:使用 Forms9Patch 将 pdf 转换为字节数组以创建 pdf,然后使用字节数组打印到蓝牙打印机
- javascript - 尝试自定义 Facebook 分享按钮时出错
- php - Woocommerce:将基于密钥的类添加到“wc_display_item_meta”中的 LI
- c++ - Centos7 g++“to_string不在std的成员中”
- entity-framework - 如何在 EF6 中表示和过滤相关数据模型
- javascript - 在 html 表单上执行 onchange 事件后如何保留值?
- python - 从命令行解析端口号