| 1 | import subprocess |
| 2 | import sys |
| 3 | import importlib |
| 4 | |
| 5 | def install_and_import(package_name, import_name=None): |
| 6 | """ |
| 7 | Installs a package using pip and imports it without restarting the script. |
| 8 | :param package_name: The name of the package to install (e.g., 'scikit-learn') |
| 9 | :param import_name: The actual name used in code (e.g., 'sklearn'). |
| 10 | Defaults to package_name if not provided. |
| 11 | """ |
| 12 | if import_name is None: |
| 13 | import_name = package_name |
| 14 | |
| 15 | try: |
| 16 | # Check if the module is already installed |
| 17 | importlib.import_module(import_name) |
| 18 | print(f"'{import_name}' is already installed. Skipping installation.") |
| 19 | except ImportError: |
| 20 | # If not found, install it |
| 21 | print(f"'{package_name}' not found. Installing...") |
| 22 | subprocess.check_call([sys.executable, "-m", "pip", "install", package_name]) |
| 23 | |
| 24 | # Load the newly installed module into the global namespace |
| 25 | globals()[import_name] = importlib.import_module(import_name) |
| 26 | print(f"Successfully installed and imported '{import_name}'.") |
| 27 | |
| 28 | # Example Usage: |
| 29 | install_and_import('requests') |
| 30 | |
| 31 | # Now you can use it immediately |
| 32 | res = requests.get("https://google.com") |
| 33 | print(f"Connection status: {res.status_code}") |
To add a comment, please login or register first.
Register or Login