[英]Converting python 2.7 Script to python 3.8
我在 AWS 中有這個 python 腳本,它會自動為我創建快照備份。 我需要將它從 Python 2.7 轉換為 Python 3.8,並且已經根據其他研究更新了“打印”(“函數”),但無法找出它仍然不起作用的原因。
這是我最初復制粘貼的作品。 我不知道 python 代碼:):(
任何幫助是極大的贊賞。
import boto3
import collections
import datetime
ec = boto3.client('ec2')
def lambda_handler(event, context):
reservations = ec.describe_instances(
Filters=[
{'Name': 'tag-key', 'Values': ['backup', 'Backup']},
]
).get(
'Reservations', []
)
instances = [
i for r in reservations
for i in r['Instances']
]
print ('Found %d instances that need backing up') % len(instances)
to_tag = collections.defaultdict(list)
for instance in instances:
try:
retention_days = [
int(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Snap-Retention'][0]
except IndexError:
retention_days = 2
for dev in instance['BlockDeviceMappings']:
if dev.get('Ebs', None) is None:
continue
vol_id = dev['Ebs']['VolumeId']
print ("Found EBS volume %s on instance %s") % (
vol_id, instance['InstanceId'])
snap = ec.create_snapshot(
VolumeId=vol_id,
)
to_tag[retention_days].append(snap['SnapshotId'])
print ('Retaining snapshot %s of volume %s from instance %s for %d days') % (
snap['SnapshotId'],
vol_id,
instance['InstanceId'],
retention_days,
)
for retention_days in to_tag.keys():
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%Y-%m-%d')
print ('Will delete %d snapshots on %s') % (len(to_tag[retention_days]), delete_fmt)
ec.create_tags(
Resources=to_tag[retention_days],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
]
)
錯誤:[ERROR] TypeError:% 不支持的操作數類型:'NoneType' 和 'int' Traceback(最后一次調用):文件“/var/task/lambda_function.py”,第 21 行,lambda_handler 打印('找到 %d 個需要備份的實例') % len(instances)
你的問題在這一行:
print ('Found %d instances that need backing up') % len(instances)
您似乎在嘗試格式化輸出,但在提供值之前關閉了print
調用。 請參閱有關 Python 輸出格式的文檔和教程,以獲得您想要的內容,無論是在此處還是在您程序的其他位置。
不要轉換 python 腳本,而是使用 AWS Backup。 AWS Backup 根據實例標簽自動處理備份。 您可以將其設置為在特定時間觸發等等。 由於您已經在此處通過實例上的標簽指定了備份,因此這將是一個簡單的切換,並且您以后不必再對 Python 腳本進行調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.