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)
添加回答
舉報