的Python脚本错误 - 尝试,除了内部的for循环 - 语法错误
问题描述:
我试图在执行我得到一个错误使用后述的“python脚本”中(“AWS LAMBDA”)来调用一个函数包含该行中的一个 “for循环:尝试&除了”的Python脚本错误 - 尝试,除了内部的for循环 - 语法错误
脚本用来创建现有AWS实例
ParseError: bad input on line 48
的AMI 48线说:
43 for instance in instances:
44 try:
46 retention_days = [
47 int(t.get('Value')) for t in instance['Tags']
48 if t['Key'] == 'Retention'][0]
49 except IndexError:
50 retention_days = 7
我尝试添加“最后:”关闭尝试:如下
43. for instance in instances:
44. try:
45. retention_days = [
46. int(t.get('Value')) for t in instance['Tags']
47. if t['Key'] == 'Retention'][0]
48. finally:
49. retention_days.close()
50. except IndexError:
51. retention_days = 7
但我仍得到相同的错误,因为我是新来的蟒蛇,我不知道如何克服这个例外。
完整的脚本可在GitHub-AMI-Creation-Script
答
在你的代码的finally
子句是放错了地方。它应该是在同一缩进层次try
和except
,例如:
try:
<some code>
except IndexError:
<some code>
finally:
<some code>
的finally
子句中的代码将始终无论是否有异常或不执行。这通常用于清理或释放资源。
答
您在try中的代码相当混乱,它看起来似乎没有正确读取。
您正在解析t.get('Value')为int,但尚未创建t,因为您在同一行上执行了此操作,而您在实例中['Tags']缺少t':'
我没有测试过这一点,随意改变它或与它玩,但,这可能有助于朝着自己的目标:
for instance in instances:
try:
for t in instance['Tags']:
if t['Key'] == 'Retention':
retention_days = int(t['Value'])
except IndexError:
retention_days = 7
希望这有助于
@gamaat:谢谢你的指正,让我尝试对代码进行如下更改:**'例如在实例中: 尝试:如果t ['Key'] =='Retention'] [0] (IndexError: retention_days = 7),则实例['标签']中的t为int(t.get('Value')) \t最后: retention_days.close()“** 不知道我用最后千钧一发是正确的 – Subash