import subprocess import sys import importlib def install_and_import(package_name, import_name=None): """ Installs a package using pip and imports it without restarting the script. :param package_name: The name of the package to install (e.g., 'scikit-learn') :param import_name: The actual name used in code (e.g., 'sklearn'). Defaults to package_name if not provided. """ if import_name is None: import_name = package_name try: # Check if the module is already installed importlib.import_module(import_name) print(f"'{import_name}' is already installed. Skipping installation.") except ImportError: # If not found, install it print(f"'{package_name}' not found. Installing...") subprocess.check_call([sys.executable, "-m", "pip", "install", package_name]) # Load the newly installed module into the global namespace globals()[import_name] = importlib.import_module(import_name) print(f"Successfully installed and imported '{import_name}'.") # Example Usage: install_and_import('requests') # Now you can use it immediately res = requests.get("https://google.com") print(f"Connection status: {res.status_code}")