this python 2.7 print code has to be converted to Python 3.7 code
print "Found %d instances that need backing up" % len(instances)
print "Retaining snapshot %s of volume %s from instance %s for %d days" % (
snap['SnapshotId'],
vol_id,
instance['InstanceId'],
retention_days,
)
this code is giving error
print("Found %d instances that need backing up" % len(instances))
print("Retaining snapshot %s of volume %s from instance %s for %d days" % (
snap['SnapshotId'],
vol_id,
instance['InstanceId'],
retention_days,
))
Please let me know how we can convert this print to python 3.7
Naib
April 18, 2021, 8:04pm
2
First install 2to3 module pip install 2to3
. Then in the console type 2to3 yourfile name.py -w
You can use some flags for more customization:
the -w
flag to enable writeback
the -n
to disable backups
1 Like
Hi Naib, I used the 2to3 module.
But still, I get errors on Print on Python 3.7 on AWS Lambda.
I get below full errors.
{
âerrorMessageâ: âSyntax error in module âlambda_functionâ: invalid syntax (lambda_function.py, line 22)â,
âerrorTypeâ: âRuntime.UserCodeSyntaxErrorâ,
âstackTraceâ: [
" File â/var/task/lambda_function.pyâ Line 22\n print âFound %d instances that need backing upâ % len(instances)\n"
]
}
Function Logs
START RequestId: 8a2824a5-edd9-4243-b54a-d40782325f2f Version: $LATEST
[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module âlambda_functionâ: invalid syntax (lambda_function.py, line 22)
Traceback (most recent call last):
File â/var/task/lambda_function.pyâ Line 22
print âFound %d instances that need backing upâ % len(instances)
END RequestId: 8a2824a5-edd9-4243-b54a-d40782325f2f
REPORT RequestId: 8a2824a5-edd9-4243-b54a-d40782325f2f Duration: 21.14 ms Billed Duration: 22 ms Memory Size: 128 MB Max Memory Used: 48 MB Init Duration: 122.09 ms
Request ID
8a2824a5-edd9-4243-b54a-d40782325f2f
Hi Naib, this is the full python 2.7 script, that has to be run in AWS Lambda python 3.7
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 = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
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'] == 'Retention'][0]
except IndexError:
retention_days = 7
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},
]
)
print(f"Found {len(instances)} that need backing up") #notice the f before the string
print(f"Retaining snapshot {snap['SnapshotId']} of volume {vol_id} from instance {instance['InstanceId']} for {retention_days} days")
the expression between curly braces will be evaluated and transformed to str.
you can also use string method format for better organization of code.
print("Found {num_of_instances} instances that need backing up".format(num_of_instances=len(instances)))
Search for python3 string formatting, the way you did it with % is the old way and is less emphasized nowadays.
Thanks Nzz,
It got resolved. I had click on Deploy button on AWS Lambda, and then run it.
Thanks everyone for helpâŚ
print("Found {} instances that need backing up".format(len(instances)))
Even this can work , the content inside curly braces is just a place holder to extract values orderly from format()
Thanks Sargun⌠I clicked on Deploy, and it started working
system
Closed
October 23, 2021, 12:13am
9
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.