Last active
February 9, 2025 22:27
-
-
Save code-yeongyu/6470c488bfbc9c74748729d79592e343 to your computer and use it in GitHub Desktop.
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
from typing import TYPE_CHECKING, Optional | |
def import_or_install(package: str, submodule: Optional[str] = None): | |
try: | |
if submodule: | |
module = __import__(f"{package}.{submodule}", fromlist=[submodule]) | |
else: | |
module = __import__(package) | |
return module | |
except ImportError: | |
print(f"Installing {package}...") | |
import subprocess | |
import sys | |
subprocess.check_call([sys.executable, "-m", "pip", "install", package]) | |
if submodule: | |
module = __import__(f"{package}.{submodule}", fromlist=[submodule]) | |
else: | |
module = __import__(package) | |
return module | |
prompt = import_or_install("rich", "prompt") # type: ignore | |
if TYPE_CHECKING: # for type checking | |
from rich import prompt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment