How to check if Python app is running within AWS lambda function? How to check if Python app is running within AWS lambda function? python python

How to check if Python app is running within AWS lambda function?


This works for me

os.environ.get("AWS_EXECUTION_ENV") is not None

EDIT: I find the existence of the context object insufficient for such a check because you might be mocking it when not running within an AWS lambda function. Then again, you may be mocking the AWS_EXECUTION_ENV as well ...


EDIT: See the other answer, this is a better solution:

os.environ.get("AWS_EXECUTION_ENV") is not None

Original answer:

How about checking for the existence of the context object in the handler function? http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html


For unit testing I use the structure:

+ my_function/+- __init__.py - empty files+- code/   +- __init__.py   +- lambda_function.py+- unittest/   +- __init__.py   +- tests.py - from ..code.lambda_function import *

When running unit tests with python -m my_function.unittest.tests, in lambda_function.py the __name__ == 'my_function.code.lambda_function'.

When running in the Lambda running, __name__ == 'lambda_function'. Note that you'll get the same value if you run with python -m my_function.code.lambda_function so you'll always need a wrapper.