将python 2.7脚本转换为python 3.8

时间:2019-12-13 18:08:58

标签: python aws-lambda

我在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},
                ]
            )

错误: [错误] TypeError:%不支持的操作数类型:“ NoneType”和“ int” 追溯(最近一次通话): lambda_handler中的文件“ /var/task/lambda_function.py”,第21行 打印(“找到需要备份的%d个实例”)%len(instances)

2 个答案:

答案 0 :(得分:1)

您的问题在这一行:

    print ('Found %d instances that need backing up') % len(instances)

您似乎正在尝试格式化输出,但是在提供值之前关闭了print调用。请参阅有关Python输出格式的文档和教程,以获取所需的内容,无论是在此处还是在程序的其他位置。

答案 1 :(得分:1)

不要转换python脚本,请改用AWS Backup。 AWS Backup根据实例标签自动处理备份。您可以将其设置为在特定时间触发。由于您已经在此处通过实例上的标签指定了备份,这将是一个简单的切换,并且您将来不必麻烦拍摄Python脚本。

https://aws.amazon.com/backup/