Skip to content

Instantly share code, notes, and snippets.

@abersheeran
Last active April 12, 2024 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abersheeran/d231087780f40e1ac76bfcc7a1b3ccb4 to your computer and use it in GitHub Desktop.
Save abersheeran/d231087780f40e1ac76bfcc7a1b3ccb4 to your computer and use it in GitHub Desktop.
Run Cython module
#!/usr/bin/python3.10
# -*- coding: utf-8 -*-
import asyncio
import sys
import importlib
from functools import reduce
from typing import Any
def import_from_string(import_str: str) -> Any:
module_str, _, attrs_str = import_str.partition(":")
if not module_str or not attrs_str:
raise ValueError(
f'Import string "{import_str}" must be in format "<module>:<attribute>".'
)
if "\\" in module_str or "/" in module_str:
module_str = (
module_str.removesuffix(".py")
.removesuffix(".pyc")
.replace("\\", "/")
.replace("/", ".")
)
return reduce(getattr, attrs_str.split("."), importlib.import_module(module_str))
if __name__ == "__main__":
instance = import_from_string(sys.argv[1])
if asyncio.iscoroutinefunction(instance):
asyncio.run(instance())
else:
instance()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment