Skip to content

Instantly share code, notes, and snippets.

@angusdev
Created August 17, 2024 10:08
Show Gist options
  • Select an option

  • Save angusdev/23c3c79a522dd5a23cd175ef4bc2eb6c to your computer and use it in GitHub Desktop.

Select an option

Save angusdev/23c3c79a522dd5a23cd175ef4bc2eb6c to your computer and use it in GitHub Desktop.
Python Dynamic Import Module
# apple_runner.py
class AppleRunner:
def run(self):
print("Apple")
import sys
import importlib
import re
# Utility function to convert CamelCase to snake_case
def camel_to_snake(name):
# Add an underscore before uppercase letters and convert the string to lowercase
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
# Define the main function to run the runner based on command-line argument
def main():
# Ensure that a class name is provided as an argument
if len(sys.argv) != 2:
print("Usage: python main.py <RunnerClassName>")
return
# Get the class name from the command-line argument
class_name = sys.argv[1]
try:
# Convert the class name from CamelCase to snake_case to determine the module name
module_name = "runner." + camel_to_snake(class_name)
# Dynamically import the module from the 'runner' package
module = importlib.import_module(module_name)
# Get the class from the module
runner_class = getattr(module, class_name)
# Instantiate the class
runner = runner_class()
# Call the run method
runner.run()
except ModuleNotFoundError:
print(f"Error: Module '{module_name}' not found.")
except AttributeError:
print(f"Error: Class '{class_name}' not found in module '{module_name}'.")
# Run the main function if this script is executed directly
if __name__ == "__main__":
main()
# orange_runner.py
class OrangeRunner:
def run(self):
print("Orange")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment