2 回答

TA贡献1847条经验 获得超11个赞
您需要将抛出异常的代码包装在更接近的 try/catch 中。这很可能意味着换client.Bucket(...)
行。如果您在循环中捕获异常,则可以使用continue
跳过该迭代。

TA贡献1802条经验 获得超4个赞
我的 for 循环在 try..except 块下,我尝试将 try..except 块放在 for 循环下,这解决了问题。
import boto3
import botocore, os, datetime, csv
from io import StringIO
import time, json
from datetime import timedelta
def lambda_handler(event, context):
client = boto3.resource('s3')
s3 = boto3.client('s3')
TS = datetime.datetime.today().strftime('%Y%m%d')
st = datetime.datetime.now()+ timedelta(hours = 5.5)
st = st.strftime('%Y-%m-%d %H:%M:%S')
Buck = 'mybuck'
Feed = {"key1": "test/Disk_space1_"+TS+"_0001"+".PNG",
"key2": "EC2/EC2_InstanceID_Input_File.csv",
"key3": "EC2/test2/AWSError.PNG"}
for key, value in Feed.items():
print(value)
try:
obj = client.Bucket(Buck).Object(value).load()
#print(obj)
if obj is None:
print(obj)
contents = st +' '+ key+ ' '+'File-exists!'
target_bucket = 'mybuck'
target_file = 'EC2/hello.csv'
open('/tmp/test.txt', 'a+').write(contents)
open('/tmp/test.txt', 'a+').write('\r\n')
s3.upload_file('/tmp/test.txt', Buck, target_file)
except botocore.exceptions.ClientError as error:
contents1 = st +' '+ key+ ' '+'File-doesnot-exists!'
print('File does not exists in path:',value+' '+'ErrMsg:',error)
open('/tmp/test.txt', 'a+').write(contents1)
open('/tmp/test.txt', 'a+').write('\r\n')
s3.upload_file('/tmp/test.txt', Buck, target_file)
添加回答
举报