I'm not a Python developer but I got stuck with taking over the maintenance of a Python 3.9 project that currently runs as a cronjob on an EC2 instance. I need to get it running from AWS Lambda. Currently the crontab on the EC2 instance invokes a cronjob/run.py
script that looks a little like this:
import os
import sys
from dotenv import load_dotenv
load_dotenv()
sync_events = get_sync_events()
# lots more stuff down here
The important thing here is that there is no __main__
method invoked. The crontab just treats this Python source file like a script and executes it from top to bottom.
My understanding is that the Lambda Handler needs a main method to be invoked. So I need a way to run the existing cronjob/run.py
(that again, has no main entry point) from inside the Lambda Handler, somehow:
def lambda_handler(event, context):
try:
# run everything thats in cronjob/run.py right here
raise e
except Exception as e:
raise e
if __name__ == '__main__':
lambda_handler(None, None)
So my question: do I need my Lambda Handler to have a __main__
method like the above, or is it possible to configure my Lambda to just call cronjob/run.py
directly? If not, what are the best options here? Thanks in advance!
CodePudding user response:
do I need my Lambda Handler to have a main method
No, you don't.
If you just want to run run.py
with lambda, you can keep things simple and just use:
import os
import sys
from dotenv import load_dotenv
def main(event, context):
load_dotenv()
sync_events = get_sync_events()
# lots more stuff down here
and configure the lambda function to have run.main
as the handler.
The name of the handler function, in this case main
, can be anything, but it must have event
and context
as arguments.
You can find more information on lambda handler here: https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html