#!/usr/bin/env python3 """ A script to run a lambda function locally, accepting event JSON and importing the lambda_function from a specified directory. """ import sys import json import logging from pathlib import Path import importlib.util import argh from argh import arg __version__ = "0.1.1" logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) class BinaryEncoder(json.JSONEncoder): """JSON encoder that handles bytes by decoding them to UTF-8 strings.""" def default(self, obj): if isinstance(obj, bytes): return obj.decode("utf-8", errors="replace") return super().default(obj) @arg("directory", help="directory containing lambda_function.py") def run_lambda(directory: str) -> None: """ Run a lambda function locally, accepting event JSON from stdin and importing the lambda_function from a specified directory. """ sys.path.insert(0, directory) import lambda_function # Load the event JSON from STDIN event = json.loads(sys.stdin.read()) # Run lambda function response = lambda_function.lambda_handler(event, None) if response.get("statusCode") == 200 and "body" in response: if isinstance(response["body"], bytes): response["body"] = response["body"].decode("utf-8") print(json.dumps(response["body"], indent=2, cls=BinaryEncoder)) else: print(json.dumps(response, indent=2, cls=BinaryEncoder)) sys.exit(1) if __name__ == "__main__": argh.dispatch_command(run_lambda)