Last active
April 12, 2024 08:59
-
-
Save abersheeran/d231087780f40e1ac76bfcc7a1b3ccb4 to your computer and use it in GitHub Desktop.
Run Cython module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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