meerschaum.utils.packages
Functions for managing packages and virtual environments reside here.
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4 5""" 6Functions for managing packages and virtual environments reside here. 7""" 8 9from __future__ import annotations 10 11import importlib.util, os, pathlib, re 12from meerschaum.utils.typing import Any, List, SuccessTuple, Optional, Union, Tuple, Dict, Iterable 13from meerschaum.utils.threading import Lock, RLock 14from meerschaum.utils.packages._packages import ( 15 packages, 16 all_packages, 17 get_install_names, 18 _MRSM_PACKAGE_ARCHIVES_PREFIX, 19) 20from meerschaum.utils.venv import ( 21 activate_venv, 22 deactivate_venv, 23 venv_executable, 24 venv_exec, 25 venv_exists, 26 venv_target_path, 27 inside_venv, 28 Venv, 29 init_venv, 30) 31 32_import_module = importlib.import_module 33_import_hook_venv = None 34_locks = { 35 '_pkg_resources_get_distribution': RLock(), 36 'import_versions': RLock(), 37 '_checked_for_updates': RLock(), 38 '_is_installed_first_check': RLock(), 39 'emitted_pandas_warning': RLock(), 40 'emitted_auto_install_warning': RLock(), 41 '_install_thread_locks': RLock(), 42} 43_checked_for_updates = set() 44_is_installed_first_check: Dict[Tuple[str, Optional[str], bool, bool], bool] = {} 45_install_thread_locks = {} 46_install_lock_depths = {} 47emitted_auto_install_warning = False 48 49 50#: Environment variable that turns off every implicit package installation (V4-002). 51NO_AUTO_INSTALL_ENV_VAR = 'MRSM_NO_AUTO_INSTALL' 52 53 54#: Packages that only style output (`rich`, ...): `attempt_import()` never installs them. The base 55#: wheel has no dependencies, and the formatting helpers fall back to plain text without them. 56_NEVER_AUTO_INSTALLED = frozenset({ 57 'rich', 'pygments', 'typing_extensions', 'colorama', 'more_termcolor', 58}) 59 60 61def _auto_install_allowed() -> bool: 62 """ 63 Return whether Meerschaum may install packages on its own. 64 65 This is the single guard behind `MRSM_NO_AUTO_INSTALL`. An install is *implicit* when it is 66 reached from an import or a dependency precheck (`attempt_import()`, `is_installed()`, 67 `need_update()`, bootstrapping `uv`, `pip`, `wheel`, ...) and *explicit* when the 68 caller asked for it (`pip_install()` from user code, `mrsm install packages`, 69 `install required`). Implicit installs call this; explicit ones are always allowed, but do not 70 bootstrap installers of their own while the variable is set. 71 """ 72 return os.environ.get(NO_AUTO_INSTALL_ENV_VAR, '').lower() not in ('1', 'true', 'yes') 73 74 75def _get_uv_bin() -> Optional[str]: 76 """Find uv without importing or installing any bootstrap dependencies.""" 77 import shutil 78 from meerschaum._internal.team_scope import in_team_process 79 if in_team_process(): 80 # The native Team launcher grants execution to uv on PATH. 81 return shutil.which('uv') 82 try: 83 import uv 84 return str(uv.find_uv_bin()) 85 except (ImportError, FileNotFoundError): 86 return shutil.which('uv') 87 88 89def _get_pip_install_target_path(venv: Optional[str] = 'mrsm') -> pathlib.Path: 90 """Resolve an installation target without creating it.""" 91 if venv is not None: 92 return venv_target_path(venv, allow_nonexistent=True) 93 94 import sys 95 return pathlib.Path(sys.prefix) 96 97 98def get_pip_install_lock_path(venv: Optional[str] = 'mrsm') -> pathlib.Path: 99 """Return the cross-process package installation lock path for an environment.""" 100 import hashlib 101 import tempfile 102 target_path = _get_pip_install_target_path(venv).resolve() 103 target_key = os.path.normcase(str(target_path)) 104 target_hash = hashlib.sha256(target_key.encode('utf-8')).hexdigest()[:16] 105 return ( 106 pathlib.Path(tempfile.gettempdir()) 107 / 'meerschaum-package-installs' 108 / (target_hash + '.lock') 109 ) 110 111 112def _pip_install_lock(venv: Optional[str] = 'mrsm'): 113 """Serialize package mutations across threads and processes for an environment.""" 114 from contextlib import contextmanager 115 116 @contextmanager 117 def _locked(): 118 from threading import get_ident 119 from meerschaum.utils.locks import InterProcessLock 120 121 lock_path = get_pip_install_lock_path(venv) 122 lock_key = str(lock_path) 123 with _locks['_install_thread_locks']: 124 thread_lock = _install_thread_locks.setdefault(lock_key, RLock()) 125 126 with thread_lock: 127 depth_key = (get_ident(), lock_key) 128 depth = _install_lock_depths.get(depth_key, 0) 129 _install_lock_depths[depth_key] = depth + 1 130 try: 131 if depth: 132 yield 133 return 134 lock_path.parent.mkdir(parents=True, exist_ok=True) 135 with InterProcessLock(lock_path): 136 yield 137 finally: 138 if depth: 139 _install_lock_depths[depth_key] -= 1 140 else: 141 _install_lock_depths.pop(depth_key, None) 142 143 return _locked() 144 145 146def _locked_pip_install(func): 147 """Lock package mutations while preserving `pip_install()`'s public signature.""" 148 import functools 149 150 @functools.wraps(func) 151 def _wrapped(*args, **kw): 152 if kw.get('dry_run', False): 153 return func(*args, **kw) 154 if kw.get('_implicit', False) and not _auto_install_allowed(): 155 return False 156 with _pip_install_lock(kw.get('venv', 'mrsm')): 157 return func(*args, **kw) 158 159 return _wrapped 160 161 162def get_module_path( 163 import_name: str, 164 venv: Optional[str] = 'mrsm', 165 debug: bool = False, 166 _try_install_name_on_fail: bool = True, 167) -> Union[pathlib.Path, None]: 168 """ 169 Get a module's path without importing. 170 """ 171 import site 172 if debug: 173 from meerschaum.utils.debug import dprint 174 if not _try_install_name_on_fail: 175 install_name = _import_to_install_name(import_name, with_version=False) 176 install_name_lower = install_name.lower().replace('-', '_') 177 import_name_lower = install_name_lower 178 else: 179 import_name_lower = import_name.lower().replace('-', '_') 180 181 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 182 if not vtp.exists(): 183 if debug: 184 dprint( 185 ( 186 "Venv '{venv}' does not exist, cannot import " 187 + f"'{import_name}'." 188 ), 189 color = False, 190 ) 191 return None 192 193 venv_target_candidate_paths = [vtp] 194 if venv is None: 195 site_user_packages_dirs = [ 196 pathlib.Path(site.getusersitepackages()) 197 ] if not inside_venv() else [] 198 site_packages_dirs = [pathlib.Path(path) for path in site.getsitepackages()] 199 200 paths_to_add = [ 201 path 202 for path in site_user_packages_dirs + site_packages_dirs 203 if path not in venv_target_candidate_paths 204 ] 205 venv_target_candidate_paths += paths_to_add 206 207 candidates = [] 208 for venv_target_candidate in venv_target_candidate_paths: 209 try: 210 file_names = os.listdir(venv_target_candidate) 211 except FileNotFoundError: 212 continue 213 for file_name in file_names: 214 file_name_lower = file_name.lower().replace('-', '_') 215 if not file_name_lower.startswith(import_name_lower): 216 continue 217 if file_name.endswith('dist_info'): 218 continue 219 file_path = venv_target_candidate / file_name 220 221 ### Most likely: Is a directory with __init__.py 222 if file_name_lower == import_name_lower and file_path.is_dir(): 223 init_path = file_path / '__init__.py' 224 if init_path.exists(): 225 candidates.append(init_path) 226 227 ### May be a standalone .py file. 228 elif file_name_lower == import_name_lower + '.py': 229 candidates.append(file_path) 230 231 ### Compiled wheels (e.g. pyodbc) 232 elif file_name_lower.startswith(import_name_lower + '.'): 233 candidates.append(file_path) 234 235 if len(candidates) == 1: 236 return candidates[0] 237 238 if not candidates: 239 if _try_install_name_on_fail: 240 return get_module_path( 241 import_name, venv=venv, debug=debug, 242 _try_install_name_on_fail=False 243 ) 244 return None 245 246 specs_paths = [] 247 for candidate_path in candidates: 248 spec = importlib.util.spec_from_file_location(import_name, str(candidate_path)) 249 if spec is not None: 250 return candidate_path 251 252 return None 253 254 255def manually_import_module( 256 import_name: str, 257 venv: Optional[str] = 'mrsm', 258 check_update: bool = True, 259 check_pypi: bool = False, 260 install: bool = True, 261 split: bool = True, 262 warn: bool = True, 263 color: bool = True, 264 debug: bool = False, 265 use_sys_modules: bool = True, 266) -> Union['ModuleType', None]: 267 """ 268 Manually import a module from a virtual environment (or the base environment). 269 270 Parameters 271 ---------- 272 import_name: str 273 The name of the module. 274 275 venv: Optional[str], default 'mrsm' 276 The virtual environment to read from. 277 278 check_update: bool, default True 279 If `True`, examine whether the available version of the package meets the required version. 280 281 check_pypi: bool, default False 282 If `True`, check PyPI for updates before importing. 283 284 install: bool, default True 285 If `True`, install the package if it's not installed or needs an update. 286 287 split: bool, default True 288 If `True`, split `import_name` on periods to get the package name. 289 290 warn: bool, default True 291 If `True`, raise a warning if the package cannot be imported. 292 293 color: bool, default True 294 If `True`, use color output for debug and warning text. 295 296 debug: bool, default False 297 Verbosity toggle. 298 299 use_sys_modules: bool, default True 300 If `True`, return the module in `sys.modules` if it exists. 301 Otherwise continue with manually importing. 302 303 Returns 304 ------- 305 The specified module or `None` if it can't be imported. 306 307 """ 308 import sys 309 _previously_imported = import_name in sys.modules 310 if _previously_imported and use_sys_modules: 311 return sys.modules[import_name] 312 313 from meerschaum.utils.warnings import warn as warn_function 314 import warnings 315 root_name = import_name.split('.')[0] if split else import_name 316 install_name = _import_to_install_name(root_name) 317 318 root_path = get_module_path(root_name, venv=venv) 319 if root_path is None: 320 return None 321 322 mod_path = root_path 323 if mod_path.is_dir(): 324 for _dir in import_name.split('.')[:-1]: 325 mod_path = mod_path / _dir 326 possible_end_module_filename = import_name.split('.')[-1] + '.py' 327 try: 328 mod_path = ( 329 (mod_path / possible_end_module_filename) 330 if possible_end_module_filename in os.listdir(mod_path) 331 else ( 332 mod_path / import_name.split('.')[-1] / '__init__.py' 333 ) 334 ) 335 except Exception: 336 mod_path = None 337 338 spec = ( 339 importlib.util.find_spec(import_name) 340 if mod_path is None or not mod_path.exists() 341 else importlib.util.spec_from_file_location(import_name, str(mod_path)) 342 ) 343 root_spec = ( 344 importlib.util.find_spec(root_name) 345 if not root_path.exists() 346 else importlib.util.spec_from_file_location(root_name, str(root_path)) 347 ) 348 349 ### Check for updates before importing. 350 _version = ( 351 determine_version( 352 pathlib.Path(root_spec.origin), 353 import_name=root_name, venv=venv, debug=debug 354 ) if root_spec is not None and root_spec.origin is not None else None 355 ) 356 357 if _version is not None: 358 if check_update: 359 if need_update( 360 None, 361 import_name=root_name, 362 version=_version, 363 check_pypi=check_pypi, 364 debug=debug, 365 ): 366 ### An installed package that is too old (or has a newer release) is never 367 ### replaced behind the user's back: say how to upgrade it. 368 if warn: 369 warn_function( 370 f"The installed '{root_name}' ({_version}) is older than what is " 371 f"required or available. Upgrade it with `mrsm upgrade packages " 372 f"{root_name}`.", 373 stack=False, 374 color=False, 375 ) 376 spec = ( 377 importlib.util.find_spec(import_name) 378 if mod_path is None or not mod_path.exists() 379 else importlib.util.spec_from_file_location(import_name, str(mod_path)) 380 ) 381 382 if spec is None: 383 try: 384 mod = _import_module(import_name) 385 except Exception: 386 mod = None 387 return mod 388 389 with Venv(venv, debug=debug): 390 mod = importlib.util.module_from_spec(spec) 391 old_sys_mod = sys.modules.get(import_name, None) 392 sys.modules[import_name] = mod 393 394 try: 395 with warnings.catch_warnings(): 396 warnings.filterwarnings('ignore', 'The NumPy') 397 spec.loader.exec_module(mod) 398 except Exception: 399 pass 400 mod = _import_module(import_name) 401 if old_sys_mod is not None: 402 sys.modules[import_name] = old_sys_mod 403 else: 404 del sys.modules[import_name] 405 406 return mod 407 408 409def _import_to_install_name(import_name: str, with_version: bool = True) -> str: 410 """ 411 Try to translate an import name to an installation name. 412 """ 413 install_name = all_packages.get(import_name, import_name) 414 if with_version: 415 return install_name 416 return get_install_no_version(install_name) 417 418 419def _import_to_dir_name(import_name: str) -> str: 420 """ 421 Translate an import name to the package name in the sites-packages directory. 422 """ 423 import re 424 return re.split( 425 r'[<>=\[]', all_packages.get(import_name, import_name) 426 )[0].replace('-', '_').lower() 427 428 429def _install_to_import_name(install_name: str) -> str: 430 """ 431 Translate an installation name to a package's import name. 432 """ 433 _install_no_version = get_install_no_version(install_name) 434 return get_install_names().get(_install_no_version, _install_no_version) 435 436 437def get_install_no_version(install_name: str) -> str: 438 """ 439 Strip the version information from the install name. 440 """ 441 import re 442 return re.split(r'[\[=<>,! \]]', install_name)[0] 443 444 445import_versions = {} 446def determine_version( 447 path: pathlib.Path, 448 import_name: Optional[str] = None, 449 venv: Optional[str] = 'mrsm', 450 search_for_metadata: bool = True, 451 split: bool = True, 452 warn: bool = False, 453 debug: bool = False, 454) -> Union[str, None]: 455 """ 456 Determine a module's `__version__` string from its filepath. 457 458 First it searches for pip metadata, then it attempts to import the module in a subprocess. 459 460 Parameters 461 ---------- 462 path: pathlib.Path 463 The file path of the module. 464 465 import_name: Optional[str], default None 466 The name of the module. If omitted, it will be determined from the file path. 467 Defaults to `None`. 468 469 venv: Optional[str], default 'mrsm' 470 The virtual environment of the Python interpreter to use if importing is necessary. 471 472 search_for_metadata: bool, default True 473 If `True`, search the pip site_packages directory (assumed to be the parent) 474 for the corresponding dist-info directory. 475 476 warn: bool, default True 477 If `True`, raise a warning if the module fails to import in the subprocess. 478 479 split: bool, default True 480 If `True`, split the determined import name by periods to get the room name. 481 482 Returns 483 ------- 484 The package's version string if available or `None`. 485 If multiple versions are found, it will trigger an import in a subprocess. 486 487 """ 488 with _locks['import_versions']: 489 if venv not in import_versions: 490 import_versions[venv] = {} 491 import os 492 old_cwd = os.getcwd() 493 from meerschaum.utils.warnings import warn as warn_function 494 if import_name is None: 495 import_name = path.parent.stem if path.stem == '__init__' else path.stem 496 import_name = import_name.split('.')[0] if split else import_name 497 if import_name in import_versions[venv]: 498 return import_versions[venv][import_name] 499 _version = None 500 module_parent_dir = ( 501 path.parent.parent if path.stem == '__init__' else path.parent 502 ) if path is not None else venv_target_path(venv, allow_nonexistent=True, debug=debug) 503 504 if not module_parent_dir.exists(): 505 return None 506 507 installed_dir_name = _import_to_dir_name(import_name) 508 clean_installed_dir_name = installed_dir_name.lower().replace('-', '_') 509 510 ### First, check if a dist-info directory exists. 511 _found_versions = [] 512 if search_for_metadata: 513 try: 514 filenames = os.listdir(module_parent_dir) 515 except FileNotFoundError: 516 filenames = [] 517 for filename in filenames: 518 if not filename.endswith('.dist-info'): 519 continue 520 filename_lower = filename.lower() 521 if not filename_lower.startswith(clean_installed_dir_name + '-'): 522 continue 523 _v = filename.replace('.dist-info', '').split("-")[-1] 524 _found_versions.append(_v) 525 526 if len(_found_versions) == 1: 527 _version = _found_versions[0] 528 with _locks['import_versions']: 529 import_versions[venv][import_name] = _version 530 return _found_versions[0] 531 532 if not _found_versions: 533 try: 534 import importlib.metadata as importlib_metadata 535 except ImportError: 536 importlib_metadata = attempt_import( 537 'importlib_metadata', 538 debug=debug, check_update=False, precheck=False, 539 color=False, check_is_installed=False, lazy=False, 540 ) 541 try: 542 os.chdir(module_parent_dir) 543 _version = importlib_metadata.metadata(import_name)['Version'] 544 except Exception: 545 _version = None 546 finally: 547 os.chdir(old_cwd) 548 549 if _version is not None: 550 with _locks['import_versions']: 551 import_versions[venv][import_name] = _version 552 return _version 553 554 if debug: 555 print(f'Found multiple versions for {import_name}: {_found_versions}') 556 557 module_parent_dir_str = module_parent_dir.as_posix() 558 559 ### Not a pip package, so let's try importing the module directly (in a subprocess). 560 _no_version_str = 'no-version' 561 code = ( 562 f"import sys, importlib; sys.path.insert(0, '{module_parent_dir_str}');\n" 563 + f"module = importlib.import_module('{import_name}');\n" 564 + "try:\n" 565 + " print(module.__version__ , end='')\n" 566 + "except:\n" 567 + f" print('{_no_version_str}', end='')" 568 ) 569 from meerschaum.config.environment import get_child_env 570 exit_code, stdout_bytes, stderr_bytes = venv_exec( 571 code, venv=venv, with_extras=True, env=get_child_env(), debug=debug 572 ) 573 stdout, stderr = stdout_bytes.decode('utf-8'), stderr_bytes.decode('utf-8') 574 _version = stdout.split('\n')[-1] if exit_code == 0 else None 575 _version = _version if _version != _no_version_str else None 576 577 if _version is None: 578 _version = _get_package_metadata(import_name, venv).get('version', None) 579 if _version is None and warn: 580 warn_function( 581 f"Failed to determine a version for '{import_name}':\n{stderr}", 582 stack = False 583 ) 584 585 ### If `__version__` doesn't exist, return `None`. 586 import_versions[venv][import_name] = _version 587 return _version 588 589 590def _get_package_metadata(import_name: str, venv: Optional[str]) -> Dict[str, str]: 591 """ 592 Read installed distribution metadata with the standard library. 593 This is useful for getting a version when no `__version__` is defined 594 and multiple versions are installed. 595 596 Parameters 597 ---------- 598 import_name: str 599 The package's import or installation name. 600 601 venv: Optional[str] 602 The virtual environment which contains the package. 603 604 Returns 605 ------- 606 A dictionary of distribution metadata with lowercase keys. 607 """ 608 from importlib import metadata 609 install_name = _import_to_install_name(import_name, with_version=False) 610 if install_name.startswith(_MRSM_PACKAGE_ARCHIVES_PREFIX): 611 return {} 612 if venv is None: 613 try: 614 distributions = [metadata.distribution(install_name)] 615 except metadata.PackageNotFoundError: 616 return {} 617 else: 618 target = venv_target_path(venv, allow_nonexistent=True) 619 if not target.exists(): 620 return {} 621 distributions = metadata.distributions(path=[str(target)]) 622 623 normalize = lambda name: re.sub(r'[-_.]+', '-', name).lower() 624 for distribution in distributions: 625 meta = distribution.metadata 626 if normalize(meta.get('Name', '')) != normalize(install_name): 627 continue 628 return {k.lower(): v for k, v in meta.items() if v and 'UNKNOWN' not in v} 629 return {} 630 631 632def _version_satisfies( 633 version: str, 634 required_version: str, 635 debug: bool = False, 636) -> Optional[bool]: 637 """ 638 Match an installed version against a PEP 440 requirement without installing anything. 639 640 Uses the Rust comparison (`meerschaum._core.version_satisfies`), then `packaging` if it is 641 importable. Returns `None` when neither can answer. 642 """ 643 if debug: 644 from meerschaum.utils.debug import dprint 645 required_version = required_version.strip() 646 if not required_version: 647 return True 648 649 try: 650 from meerschaum import _core 651 satisfied = _core.version_satisfies(version, required_version) 652 except (ImportError, AttributeError): 653 satisfied = None 654 if satisfied is not None: 655 return satisfied 656 657 specifiers, packaging_version = attempt_import( 658 'packaging.specifiers', 659 'packaging.version', 660 install=False, 661 warn=False, 662 lazy=False, 663 check_update=False, 664 ) 665 if specifiers is not None and packaging_version is not None: 666 try: 667 return specifiers.SpecifierSet(required_version, prereleases=True).contains( 668 packaging_version.Version(version) 669 ) 670 except Exception as e: 671 if debug: 672 dprint(f"`packaging` could not match '{version}' to '{required_version}': {e}") 673 674 if debug: 675 dprint( 676 f"No version parser is available to match '{version}' to '{required_version}'; " 677 + "assuming the requirement is satisfied." 678 ) 679 return None 680 681 682def need_update( 683 package: Optional['ModuleType'] = None, 684 install_name: Optional[str] = None, 685 import_name: Optional[str] = None, 686 version: Optional[str] = None, 687 check_pypi: bool = False, 688 split: bool = True, 689 color: bool = True, 690 debug: bool = False, 691 _run_determine_version: bool = True, 692) -> bool: 693 """ 694 Check if a Meerschaum dependency needs an update. 695 Returns a bool for whether or not a package needs to be updated. 696 697 Parameters 698 ---------- 699 package: 'ModuleType' 700 The module of the package to be updated. 701 702 install_name: Optional[str], default None 703 If provided, use this string to determine the required version. 704 Otherwise use the install name defined in `meerschaum.utils.packages._packages`. 705 706 import_name: 707 If provided, override the package's `__name__` string. 708 709 version: Optional[str], default None 710 If specified, override the package's `__version__` string. 711 712 check_pypi: bool, default False 713 If `True`, check pypi.org for updates. 714 Defaults to `False`. 715 716 split: bool, default True 717 If `True`, split the module's name on periods to detrive the root name. 718 Defaults to `True`. 719 720 color: bool, default True 721 If `True`, format debug output. 722 Defaults to `True`. 723 724 debug: bool, default True 725 Verbosity toggle. 726 727 Returns 728 ------- 729 A bool indicating whether the package requires an update. 730 731 """ 732 if debug: 733 from meerschaum.utils.debug import dprint 734 from meerschaum.utils.warnings import warn as warn_function 735 import re 736 root_name = ( 737 package.__name__.split('.')[0] if split else package.__name__ 738 ) if import_name is None else ( 739 import_name.split('.')[0] if split else import_name 740 ) 741 install_name = install_name or _import_to_install_name(root_name) 742 auto_install_allowed = _auto_install_allowed() 743 ### Asking PyPI for the latest release is an implicit network request. 744 check_pypi = check_pypi and auto_install_allowed 745 with _locks['_checked_for_updates']: 746 if install_name in _checked_for_updates: 747 return False 748 _checked_for_updates.add(install_name) 749 750 _install_no_version = get_install_no_version(install_name) 751 required_version = ( 752 install_name 753 .replace(_install_no_version, '') 754 ) 755 if ']' in required_version: 756 required_version = required_version.split(']')[1] 757 758 ### No minimum version was specified, and we're not going to check PyPI. 759 if not required_version and not check_pypi: 760 return False 761 762 ### NOTE: Sometimes (rarely), we depend on a development build of a package. 763 if '.dev' in required_version: 764 required_version = required_version.split('.dev')[0] 765 if version and '.dev' in version: 766 version = version.split('.dev')[0] 767 768 try: 769 if not version: 770 if not _run_determine_version: 771 version = determine_version( 772 pathlib.Path(package.__file__), 773 import_name=root_name, warn=False, debug=debug 774 ) 775 if version is None: 776 return False 777 except Exception as e: 778 if debug: 779 dprint(str(e), color=color) 780 dprint("No version could be determined from the installed package.", color=color) 781 return False 782 raw_version = version 783 split_version = version.split('.') 784 last_part = split_version[-1] 785 if len(split_version) == 2: 786 version = '.'.join(split_version) + '.0' 787 elif 'dev' in last_part or 'rc' in last_part: 788 tag = 'dev' if 'dev' in last_part else 'rc' 789 last_sep = '-' 790 if not last_part.startswith(tag): 791 last_part = f'-{tag}'.join(last_part.split(tag)) 792 last_sep = '.' 793 version = '.'.join(split_version[:-1]) + last_sep + last_part 794 elif len(split_version) > 3: 795 version = '.'.join(split_version[:3]) 796 797 if check_pypi: 798 ### Check PyPI for updates 799 update_checker, packaging_version = attempt_import( 800 'update_checker', 'packaging.version', lazy=False, check_update=False, debug=debug 801 ) 802 checker = update_checker.UpdateChecker() 803 result = checker.check(_install_no_version, version) 804 else: 805 ### Skip PyPI and assume we can't be sure. 806 result = None 807 808 ### Compare PyPI's version with our own. 809 if result is not None: 810 ### We have a result from PyPI and a stated required version. 811 if required_version: 812 satisfied = _version_satisfies(result.available_version, required_version, debug=debug) 813 return (not satisfied) if satisfied is not None else False 814 815 ### If `check_pypi` and we don't have a required version, check if PyPI's version 816 ### is newer than the installed version. 817 else: 818 return ( 819 packaging_version.parse(result.available_version) > 820 packaging_version.parse(version) 821 ) 822 823 ### We might be depending on a prerelease. 824 ### Sanity check that the required version is not greater than the installed version. 825 required_version = ( 826 required_version.replace(_MRSM_PACKAGE_ARCHIVES_PREFIX, '') 827 .replace(' @ ', '').replace('wheels', '').replace('+mrsm', '').replace('/-', '') 828 .replace('-py3-none-any.whl', '') 829 ) 830 831 ### An unknown answer (neither side parses as PEP 440) must not trigger an install. 832 satisfied = _version_satisfies(raw_version, required_version, debug=debug) 833 return (not satisfied) if satisfied is not None else False 834 835 836def get_pip( 837 venv: Optional[str] = 'mrsm', 838 color: bool = True, 839 debug: bool = False, 840) -> bool: 841 """ 842 Download and run the get-pip.py script. 843 844 Parameters 845 ---------- 846 venv: Optional[str], default 'mrsm' 847 The virtual environment into which to install `pip`. 848 849 color: bool, default True 850 If `True`, force color output. 851 852 debug: bool, default False 853 Verbosity toggle. 854 855 Returns 856 ------- 857 A bool indicating success. 858 859 """ 860 import sys 861 import subprocess 862 import meerschaum.config.paths as paths 863 from meerschaum.utils.misc import wget 864 from meerschaum._internal.static import STATIC_CONFIG 865 url = STATIC_CONFIG['system']['urls']['get-pip.py'] 866 dest = paths.CACHE_RESOURCES_PATH / 'get-pip.py' 867 try: 868 wget(url, dest, color=False, debug=debug) 869 except Exception: 870 print(f"Failed to fetch pip from '{url}'. Please install pip and restart Meerschaum.") 871 sys.exit(1) 872 if venv is not None: 873 init_venv(venv=venv, debug=debug) 874 cmd_list = [venv_executable(venv=venv), dest.as_posix()] 875 return subprocess.call(cmd_list, env=_get_pip_os_env(color=color)) == 0 876 877 878def get_pip_install_plan( 879 *install_names: str, 880 args: Optional[List[str]] = None, 881 requirements_file_path: Union[pathlib.Path, str, None] = None, 882 venv: Optional[str] = 'mrsm', 883 _uninstall: bool = False, 884 _install_uv_pip: bool = True, 885 _use_uv_pip: bool = True, 886 debug: bool = False, 887) -> Dict[str, Any]: 888 """Return a read-only summary of a package installation request.""" 889 try: 890 import pip # noqa: F401 891 have_pip = True 892 except ImportError: 893 have_pip = False 894 895 uv_bin = _get_uv_bin() 896 897 use_uv_pip = bool( 898 _use_uv_pip 899 and uv_bin 900 and is_uv_enabled() 901 ) 902 requested_packages = [ 903 ( 904 get_install_no_version(install_name) 905 if _uninstall or install_name.startswith(_MRSM_PACKAGE_ARCHIVES_PREFIX) 906 else install_name 907 ) 908 for install_name in install_names 909 ] 910 auto_install_enabled = _auto_install_allowed() 911 return { 912 'operation': 'uninstall' if _uninstall else 'install', 913 'environment': venv, 914 'target': str(_get_pip_install_target_path(venv)), 915 'packages': requested_packages, 916 'requirements_file': ( 917 str(pathlib.Path(requirements_file_path).resolve()) 918 if requirements_file_path is not None 919 else None 920 ), 921 'args': list(args if args is not None else ([] if _uninstall else ['--upgrade'])), 922 'installer': 'uv' if use_uv_pip else 'pip', 923 'installer_available': bool(use_uv_pip or have_pip), 924 'pip_fallback': bool(use_uv_pip and have_pip), 925 'auto_install_enabled': auto_install_enabled, 926 'would_bootstrap_uv': bool( 927 not use_uv_pip 928 and not uv_bin 929 and have_pip 930 and _install_uv_pip 931 and is_uv_enabled() 932 ), 933 'lock_path': str(get_pip_install_lock_path(venv)), 934 } 935 936 937@_locked_pip_install 938def pip_install( 939 *install_names: str, 940 args: Optional[List[str]] = None, 941 requirements_file_path: Union[pathlib.Path, str, None] = None, 942 venv: Optional[str] = 'mrsm', 943 split: bool = False, 944 check_update: bool = True, 945 check_pypi: bool = True, 946 check_wheel: bool = True, 947 _uninstall: bool = False, 948 _from_completely_uninstall: bool = False, 949 _install_uv_pip: bool = True, 950 _use_uv_pip: bool = True, 951 _implicit: bool = False, 952 color: bool = True, 953 silent: bool = False, 954 dry_run: bool = False, 955 debug: bool = False, 956) -> bool: 957 """ 958 Install packages from PyPI with `pip`. 959 960 When `MRSM_NO_AUTO_INSTALL` is set, calling this function directly still installs the 961 requested packages, but never bootstraps `uv`, `pip`, `wheel` or `setuptools` on its own 962 and never checks PyPI for a newer `pip`. Calls made on behalf of an import or a dependency 963 precheck (`_implicit=True`) install nothing and return `False`. 964 965 Parameters 966 ---------- 967 *install_names: str 968 The installation names of packages to be installed. 969 This includes version restrictions. 970 Use `_import_to_install_name()` to get the predefined `install_name` for a package 971 from its import name. 972 973 args: Optional[List[str]], default None 974 A list of command line arguments to pass to `pip`. 975 If not provided, default to `['--upgrade']` if `_uninstall` is `False`, else `[]`. 976 977 requirements_file_path: Optional[pathlib.Path, str], default None 978 If provided, append `['-r', '/path/to/requirements.txt']` to `args`. 979 980 venv: str, default 'mrsm' 981 The virtual environment to install into. 982 983 split: bool, default False 984 If `True`, split on periods and only install the root package name. 985 986 check_update: bool, default True 987 If `True`, check if the package requires an update. 988 989 check_pypi: bool, default True 990 If `True` and `check_update` is `True`, check PyPI for the latest version. 991 992 check_wheel: bool, default True 993 If `True`, check if `wheel` is available. 994 995 _uninstall: bool, default False 996 If `True`, uninstall packages instead. 997 998 color: bool, default True 999 If `True`, include color in debug text. 1000 1001 silent: bool, default False 1002 If `True`, skip printing messages. 1003 1004 dry_run: bool, default False 1005 If `True`, print the read-only installation plan without changing the environment. 1006 1007 debug: bool, default False 1008 Verbosity toggle. 1009 1010 Returns 1011 ------- 1012 A bool indicating success. 1013 1014 """ 1015 import meerschaum.config.paths as paths 1016 from meerschaum._internal.static import STATIC_CONFIG 1017 from meerschaum.utils.warnings import warn 1018 auto_install_allowed = _auto_install_allowed() 1019 if dry_run: 1020 import json 1021 plan = get_pip_install_plan( 1022 *install_names, 1023 args=args, 1024 requirements_file_path=requirements_file_path, 1025 venv=venv, 1026 _uninstall=_uninstall, 1027 _install_uv_pip=_install_uv_pip, 1028 _use_uv_pip=_use_uv_pip, 1029 debug=debug, 1030 ) 1031 if not silent: 1032 print(json.dumps(plan, indent=2)) 1033 return True 1034 1035 if args is None: 1036 args = ['--upgrade'] if not _uninstall else [] 1037 ANSI = True if color else False 1038 daemon_env_var = STATIC_CONFIG['environment']['daemon_id'] 1039 inside_daemon = daemon_env_var in os.environ 1040 if inside_daemon: 1041 silent = True 1042 1043 _args = list(args) 1044 pip_venv = None 1045 try: 1046 import pip 1047 have_pip = True 1048 except ImportError: 1049 have_pip = False 1050 uv_bin = _get_uv_bin() 1051 have_uv_pip = uv_bin is not None 1052 1053 if ( 1054 auto_install_allowed 1055 and have_pip 1056 and not have_uv_pip 1057 and _install_uv_pip 1058 and is_uv_enabled() 1059 ): 1060 if not pip_install( 1061 'uv', 1062 venv=None, 1063 debug=debug, 1064 _install_uv_pip=False, 1065 check_update=False, 1066 check_pypi=False, 1067 check_wheel=False, 1068 ) and not silent: 1069 warn( 1070 f"Failed to install `uv` for virtual environment '{venv}'.", 1071 color=False, 1072 ) 1073 # The bootstrap may have made uv available in this interpreter or on PATH. 1074 uv_bin = _get_uv_bin() 1075 1076 use_uv_pip = ( 1077 _use_uv_pip 1078 and uv_bin is not None 1079 and is_uv_enabled() 1080 ) 1081 # uv does not need wheel, setuptools, or pip in either interpreter. Checking their 1082 # versions first recursively bootstraps the very installer we are trying to select. 1083 have_wheel = ( 1084 venv_contains_package('wheel', venv=venv, debug=debug) 1085 if check_wheel and not use_uv_pip else False 1086 ) 1087 1088 import sys 1089 if not have_pip and not use_uv_pip: 1090 have_mrsm_pip = venv_contains_package('pip', venv='mrsm') 1091 if not have_mrsm_pip and not auto_install_allowed: 1092 if not silent: 1093 warn( 1094 "Neither `uv` nor `pip` is available to install packages, " 1095 + f"and {NO_AUTO_INSTALL_ENV_VAR} forbids downloading them.", 1096 stack=False, 1097 color=False, 1098 ) 1099 return False 1100 if not have_mrsm_pip and not get_pip(venv=venv, color=color, debug=debug): 1101 import sys 1102 minor = sys.version_info.minor 1103 print( 1104 "\nFailed to import `pip` and `ensurepip`.\n" 1105 + "If you are running Ubuntu/Debian, " 1106 + f"you might need to install `python3.{minor}-distutils`:\n\n" 1107 + f" sudo apt install python3.{minor}-pip python3.{minor}-venv\n\n" 1108 + "Please install pip and restart Meerschaum.\n\n" 1109 + "You can find instructions on installing `pip` here:\n" 1110 + "https://pip.pypa.io/en/stable/installing/" 1111 ) 1112 sys.exit(1) 1113 1114 pip = attempt_import('pip', lazy=False) 1115 pip_venv = 'mrsm' 1116 1117 with Venv(venv, debug=debug): 1118 if venv is not None: 1119 if ( 1120 '--ignore-installed' not in args 1121 and '-I' not in _args 1122 and not _uninstall 1123 and not use_uv_pip 1124 ): 1125 _args += ['--ignore-installed'] 1126 if '--cache-dir' not in args and not _uninstall: 1127 cache_dir_path = paths.VIRTENV_RESOURCES_PATH / venv / 'cache' 1128 _args += ['--cache-dir', str(cache_dir_path)] 1129 1130 if 'pip' not in ' '.join(_args) and not use_uv_pip: 1131 if check_update and not _uninstall and auto_install_allowed: 1132 pip = attempt_import('pip', venv=venv, install=False, debug=debug, lazy=False) 1133 if need_update(pip, check_pypi=check_pypi, debug=debug): 1134 _args.append(all_packages['pip']) 1135 1136 _args = (['install'] if not _uninstall else ['uninstall']) + _args 1137 1138 if check_wheel and not _uninstall and not use_uv_pip and auto_install_allowed: 1139 if not have_wheel: 1140 setup_packages_to_install = ( 1141 ['setuptools', 'wheel', 'PyYAML'] 1142 + (['uv'] if is_uv_enabled() else []) 1143 ) 1144 if not pip_install( 1145 *setup_packages_to_install, 1146 venv=venv, 1147 check_update=False, 1148 check_pypi=False, 1149 check_wheel=False, 1150 debug=debug, 1151 _install_uv_pip=False, 1152 ) and not silent: 1153 from meerschaum.utils.misc import items_str 1154 warn( 1155 ( 1156 f"Failed to install {items_str(setup_packages_to_install)} for virtual " 1157 + f"environment '{venv}'." 1158 ), 1159 color=False, 1160 ) 1161 1162 if requirements_file_path is not None: 1163 _args.append('-r') 1164 _args.append(pathlib.Path(requirements_file_path).resolve().as_posix()) 1165 1166 if not ANSI and '--no-color' not in _args: 1167 _args.append('--no-color') 1168 1169 if '--no-input' not in _args and not use_uv_pip: 1170 _args.append('--no-input') 1171 1172 if _uninstall and '-y' not in _args and not use_uv_pip: 1173 _args.append('-y') 1174 1175 ### `uv pip uninstall` has no `-y` (it never prompts) and rejects it. 1176 if _uninstall and use_uv_pip: 1177 _args = [arg for arg in _args if arg not in ('-y', '--yes')] 1178 1179 if '--no-warn-conflicts' not in _args and not _uninstall and not use_uv_pip: 1180 _args.append('--no-warn-conflicts') 1181 1182 if '--disable-pip-version-check' not in _args and not use_uv_pip: 1183 _args.append('--disable-pip-version-check') 1184 1185 if '--target' not in _args and '-t' not in _args and not (not use_uv_pip and _uninstall): 1186 if venv is not None: 1187 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 1188 if not vtp.exists(): 1189 if not init_venv(venv, force=True): 1190 vtp.mkdir(parents=True, exist_ok=True) 1191 _args += ['--target', venv_target_path(venv, debug=debug).as_posix()] 1192 elif ( 1193 '--target' not in _args 1194 and '-t' not in _args 1195 and not inside_venv() 1196 and not _uninstall 1197 and not use_uv_pip 1198 ): 1199 _args.append('--user') 1200 1201 if venv is None and '--break-system-packages' not in _args: 1202 _args.append('--break-system-packages') 1203 1204 if debug: 1205 if '-v' not in _args or '-vv' not in _args or '-vvv' not in _args: 1206 if use_uv_pip: 1207 _args.append('--verbose') 1208 else: 1209 if '-q' not in _args or '-qq' not in _args or '-qqq' not in _args: 1210 pass 1211 1212 _packages = [ 1213 ( 1214 get_install_no_version(install_name) 1215 if _uninstall or install_name.startswith(_MRSM_PACKAGE_ARCHIVES_PREFIX) 1216 else install_name 1217 ) 1218 for install_name in install_names 1219 ] 1220 msg = "Installing packages:" if not _uninstall else "Uninstalling packages:" 1221 for p in _packages: 1222 msg += f'\n - {p}' 1223 if not silent: 1224 print(msg) 1225 1226 if _uninstall and not _from_completely_uninstall and not use_uv_pip: 1227 for install_name in _packages: 1228 _install_no_version = get_install_no_version(install_name) 1229 if _install_no_version in ('pip', 'wheel', 'uv'): 1230 continue 1231 if not completely_uninstall_package( 1232 _install_no_version, 1233 venv=venv, 1234 debug=debug, 1235 ) and not silent: 1236 warn( 1237 f"Failed to clean up package '{_install_no_version}'.", 1238 ) 1239 1240 ### NOTE: Only append the `--prerelease=allow` flag if we explicitly depend on a prerelease. 1241 if use_uv_pip: 1242 _args.insert(0, 'pip') 1243 if not _uninstall and get_prerelease_dependencies(_packages): 1244 _args.append('--prerelease=allow') 1245 1246 rc = run_python_package( 1247 ('pip' if not use_uv_pip else 'uv'), 1248 _args + _packages, 1249 venv=pip_venv, 1250 env=_get_pip_os_env(color=color), 1251 debug=debug, 1252 ) 1253 if debug: 1254 print(f"{rc=}") 1255 success = rc == 0 1256 1257 if success: 1258 with _locks['_is_installed_first_check']: 1259 _is_installed_first_check.clear() 1260 _update_request_ledger(_packages, venv, _uninstall) 1261 1262 msg = ( 1263 "Successfully " + ('un' if _uninstall else '') + "installed packages." if success 1264 else "Failed to " + ('un' if _uninstall else '') + "install packages." 1265 ) 1266 if not silent: 1267 print(msg) 1268 if debug and not silent: 1269 print('pip ' + ('un' if _uninstall else '') + 'install returned:', success) 1270 return success 1271 1272 1273def get_prerelease_dependencies(_packages: Optional[List[str]] = None): 1274 """ 1275 Return a list of explicitly prerelease dependencies from a list of packages. 1276 """ 1277 if _packages is None: 1278 _packages = list(all_packages.keys()) 1279 prelrease_strings = ['dev', 'rc', 'a'] 1280 prerelease_packages = [] 1281 for install_name in _packages: 1282 _install_no_version = get_install_no_version(install_name) 1283 import_name = _install_to_import_name(install_name) 1284 install_with_version = _import_to_install_name(import_name) 1285 version_only = ( 1286 install_with_version.lower().replace(_install_no_version.lower(), '') 1287 .split(']')[-1] 1288 ) 1289 1290 is_prerelease = False 1291 for prelrease_string in prelrease_strings: 1292 if prelrease_string in version_only: 1293 is_prerelease = True 1294 1295 if is_prerelease: 1296 prerelease_packages.append(install_name) 1297 return prerelease_packages 1298 1299 1300def completely_uninstall_package( 1301 install_name: str, 1302 venv: str = 'mrsm', 1303 debug: bool = False, 1304) -> bool: 1305 """ 1306 Continue calling `pip uninstall` until a package is completely 1307 removed from a virtual environment. 1308 This is useful for dealing with multiple installed versions of a package. 1309 """ 1310 attempts = 0 1311 _install_no_version = get_install_no_version(install_name) 1312 clean_install_no_version = _install_no_version.lower().replace('-', '_') 1313 installed_versions = [] 1314 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 1315 if not vtp.exists(): 1316 return True 1317 1318 for file_name in os.listdir(vtp): 1319 if not file_name.endswith('.dist-info'): 1320 continue 1321 clean_dist_info = file_name.replace('-', '_').lower() 1322 if not clean_dist_info.startswith(clean_install_no_version): 1323 continue 1324 installed_versions.append(file_name) 1325 1326 max_attempts = len(installed_versions) 1327 while attempts < max_attempts: 1328 if not venv_contains_package( 1329 _install_to_import_name(_install_no_version), 1330 venv=venv, debug=debug, 1331 ): 1332 return True 1333 if not pip_uninstall( 1334 _install_no_version, 1335 venv = venv, 1336 silent = (not debug), 1337 _from_completely_uninstall = True, 1338 debug = debug, 1339 ): 1340 return False 1341 attempts += 1 1342 return False 1343 1344 1345def pip_uninstall( 1346 *args, **kw 1347) -> bool: 1348 """ 1349 Uninstall Python packages. 1350 This function is a wrapper around `pip_install()` but with `_uninstall` enforced as `True`. 1351 """ 1352 return pip_install(*args, _uninstall=True, **{k: v for k, v in kw.items() if k != '_uninstall'}) 1353 1354 1355def run_python_package( 1356 package_name: str, 1357 args: Optional[List[str]] = None, 1358 venv: Optional[str] = 'mrsm', 1359 cwd: Optional[str] = None, 1360 env: Optional[Dict[str, str]] = None, 1361 foreground: bool = False, 1362 as_proc: bool = False, 1363 capture_output: bool = False, 1364 debug: bool = False, 1365 **kw: Any, 1366) -> Union[int, subprocess.Popen, None]: 1367 """ 1368 Runs an installed python package. 1369 E.g. Translates to `/usr/bin/python -m [package]` 1370 1371 Parameters 1372 ---------- 1373 package_name: str 1374 The Python module to be executed. 1375 1376 args: Optional[List[str]], default None 1377 Additional command line arguments to be appended after `-m [package]`. 1378 1379 venv: Optional[str], default 'mrsm' 1380 If specified, execute the Python interpreter from a virtual environment. 1381 1382 cwd: Optional[str], default None 1383 If specified, change directories before starting the process. 1384 Defaults to `None`. 1385 1386 env: Optional[Dict[str, str]], default None 1387 If specified, only use the provided dictionary for the environment variables. 1388 Defaults to `os.environ`. 1389 1390 as_proc: bool, default False 1391 If `True`, return a `subprocess.Popen` object. 1392 1393 capture_output: bool, default False 1394 If `as_proc` is `True`, capture stdout and stderr. 1395 1396 foreground: bool, default False 1397 If `True`, start the subprocess as a foreground process. 1398 Defaults to `False`. 1399 1400 kw: Any 1401 Additional keyword arguments to pass to `meerschaum.utils.process.run_process()` 1402 and by extension `subprocess.Popen()`. 1403 1404 Returns 1405 ------- 1406 Either a return code integer or a `subprocess.Popen` object 1407 (or `None` if a `KeyboardInterrupt` occurs and as_proc is `True`). 1408 """ 1409 import sys 1410 import subprocess 1411 import traceback 1412 import meerschaum.config.paths as paths 1413 from meerschaum.utils.process import run_process 1414 from meerschaum.utils.warnings import warn 1415 if args is None: 1416 args = [] 1417 old_cwd = os.getcwd() 1418 if cwd is not None: 1419 os.chdir(cwd) 1420 executable = venv_executable(venv=venv) 1421 venv_path = (paths.VIRTENV_RESOURCES_PATH / venv) if venv is not None else None 1422 from meerschaum.config.environment import get_child_env 1423 env_dict = get_child_env(env if isinstance(env, dict) else (os.environ or {})) 1424 if venv_path is not None: 1425 env_dict.update({'VIRTUAL_ENV': venv_path.as_posix()}) 1426 uv_bin = _get_uv_bin() if package_name == 'uv' else None 1427 command = ( 1428 [uv_bin] if uv_bin is not None else [executable, '-m', str(package_name)] 1429 ) + [str(a) for a in args] 1430 if debug: 1431 print(command, file=sys.stderr) 1432 try: 1433 to_return = run_process( 1434 command, 1435 foreground=foreground, 1436 as_proc=as_proc, 1437 capture_output=capture_output, 1438 env=env_dict, 1439 **kw 1440 ) 1441 except Exception: 1442 msg = f"Failed to execute {command}, will try again:\n{traceback.format_exc()}" 1443 warn(msg, color=False) 1444 stdout, stderr = ( 1445 (None, None) 1446 if not capture_output 1447 else (subprocess.PIPE, subprocess.PIPE) 1448 ) 1449 proc = subprocess.Popen( 1450 command, 1451 stdout=stdout, 1452 stderr=stderr, 1453 stdin=sys.stdin, 1454 env=env_dict, 1455 ) 1456 to_return = proc if as_proc else proc.wait() 1457 except KeyboardInterrupt: 1458 to_return = 1 if not as_proc else None 1459 os.chdir(old_cwd) 1460 return to_return 1461 1462 1463 1464def _prepared_execution_import(names, lazy, precheck, warn): 1465 """Import from native-prepared private sites without managing an environment. 1466 1467 Api and Metadata processes already have their complete import path selected by the native 1468 launcher. Activating a named venv here can attempt recovery/installation even with 1469 install=False. Standard import machinery is the only lookup needed in these processes. 1470 The marker removes side effects; it never grants access or substitutes for confinement. 1471 """ 1472 import importlib.util 1473 import sys 1474 import warnings 1475 if names == ('meerschaum',): 1476 # Match the ordinary helper's recursion guard while the SDK is initializing. 1477 return _import_module('meerschaum') 1478 modules = [] 1479 for name in names: 1480 try: 1481 module = sys.modules.get(name) 1482 if module is not None and not getattr(getattr(module, '__spec__', None), '_initializing', False): 1483 modules.append(module) 1484 continue 1485 if lazy: 1486 # This is Python's current-path lookup, with no venv/package management. 1487 # Preserve lazy imports and return None for an unavailable dependency. 1488 if precheck and importlib.util.find_spec(name) is None: 1489 raise ModuleNotFoundError(name=name) 1490 module = lazy_import(name, precheck=False, install=False, warn=warn) 1491 else: 1492 module = _import_module(name) 1493 except Exception: 1494 if warn: 1495 warnings.warn( 1496 f"Module '{name}' is unavailable in the prepared private interpreter.", 1497 ImportWarning, stacklevel=3, 1498 ) 1499 module = None 1500 modules.append(module) 1501 return modules[0] if len(modules) == 1 else tuple(modules) 1502 1503 1504def attempt_import( 1505 *names: str, 1506 lazy: bool = True, 1507 warn: bool = True, 1508 install: bool = True, 1509 venv: Optional[str] = 'mrsm', 1510 precheck: bool = True, 1511 split: bool = True, 1512 check_update: bool = False, 1513 check_pypi: bool = False, 1514 check_is_installed: bool = True, 1515 allow_outside_venv: bool = True, 1516 color: bool = True, 1517 debug: bool = False 1518) -> Any: 1519 """ 1520 Raise a warning if packages are not installed; otherwise import and return modules. 1521 If `lazy` is `True`, return lazy-imported modules. 1522 1523 Returns tuple of modules if multiple names are provided, else returns one module. 1524 1525 Parameters 1526 ---------- 1527 names: List[str] 1528 The packages to be imported. 1529 1530 lazy: bool, default True 1531 If `True`, lazily load packages. 1532 1533 warn: bool, default True 1534 If `True`, raise a warning if a package cannot be imported. 1535 1536 install: bool, default True 1537 If `True`, attempt to install a missing package into the designated virtual environment. 1538 If `check_update` is True, install updates if available. 1539 1540 venv: Optional[str], default 'mrsm' 1541 The virtual environment in which to search for packages and to install packages into. 1542 1543 precheck: bool, default True 1544 If `True`, attempt to find module before importing (necessary for checking if modules exist 1545 and retaining lazy imports), otherwise assume lazy is `False`. 1546 1547 split: bool, default True 1548 If `True`, split packages' names on `'.'`. 1549 1550 check_update: bool, default False 1551 If `True` and `install` is `True`, install updates if the required minimum version 1552 does not match. 1553 1554 check_pypi: bool, default False 1555 If `True` and `check_update` is `True`, check PyPI when determining whether 1556 an update is required. 1557 1558 check_is_installed: bool, default True 1559 If `True`, check if the package is contained in the virtual environment. 1560 1561 allow_outside_venv: bool, default True 1562 If `True`, search outside of the specified virtual environment 1563 if the package cannot be found. 1564 Setting to `False` will reinstall the package into a virtual environment, even if it 1565 is installed outside. 1566 1567 color: bool, default True 1568 If `False`, do not print ANSI colors. 1569 1570 Returns 1571 ------- 1572 The specified modules. If they're not available and `install` is `True`, it will first 1573 download them into a virtual environment and return the modules. 1574 1575 Examples 1576 -------- 1577 >>> pandas, sqlalchemy = attempt_import('pandas', 'sqlalchemy') 1578 >>> pandas = attempt_import('pandas') 1579 1580 """ 1581 1582 import importlib.util 1583 1584 if os.environ.get('MRSM_API_EXECUTION') == '1': 1585 return _prepared_execution_import(names, lazy=lazy, precheck=precheck, warn=warn) 1586 1587 global emitted_auto_install_warning 1588 no_auto_install_env_var = NO_AUTO_INSTALL_ENV_VAR 1589 if not _auto_install_allowed(): 1590 install = False 1591 1592 ### Cosmetic packages are never installed on import: without them output is plain text. 1593 if any(name.split('.')[0] in _NEVER_AUTO_INSTALLED for name in names): 1594 install = False 1595 warn = False 1596 1597 ### to prevent recursion, check if parent Meerschaum package is being imported 1598 if names == ('meerschaum',): 1599 return _import_module('meerschaum') 1600 1601 if venv == 'mrsm' and _import_hook_venv is not None: 1602 if debug: 1603 print(f"Import hook for virtual environment '{_import_hook_venv}' is active.") 1604 venv = _import_hook_venv 1605 1606 _warnings = _import_module('meerschaum.utils.warnings') 1607 warn_function = _warnings.warn 1608 1609 def do_import(_name: str, **kw) -> Union['ModuleType', None]: 1610 ### A fully-imported module resolves from `sys.modules` regardless of the active venv, 1611 ### so skip activating the venv (which resolves and creates its directories). 1612 import sys 1613 loaded_module = sys.modules.get(_name, None) 1614 if ( 1615 loaded_module is not None 1616 and not getattr(getattr(loaded_module, '__spec__', None), '_initializing', False) 1617 ): 1618 return loaded_module 1619 1620 with Venv(venv=venv, debug=debug): 1621 ### determine the import method (lazy vs normal) 1622 from meerschaum.utils.misc import filter_keywords 1623 import_method = ( 1624 _import_module if not lazy 1625 else lazy_import 1626 ) 1627 try: 1628 mod = import_method(_name, **(filter_keywords(import_method, **kw))) 1629 except Exception as e: 1630 if warn: 1631 import traceback 1632 traceback.print_exception(type(e), e, e.__traceback__) 1633 warn_function( 1634 f"Failed to import module '{_name}'.\nException:\n{e}", 1635 ImportWarning, 1636 stacklevel = (5 if lazy else 4), 1637 color = False, 1638 ) 1639 mod = None 1640 return mod 1641 1642 modules = [] 1643 for name in names: 1644 ### Check if package is a declared dependency. 1645 root_name = name.split('.')[0] if split else name 1646 install_name = _import_to_install_name(root_name) 1647 1648 if install_name is None: 1649 install_name = root_name 1650 if warn and root_name != 'plugins': 1651 warn_function( 1652 f"Package '{root_name}' is not declared in meerschaum.utils.packages.", 1653 ImportWarning, 1654 stacklevel = 3, 1655 color = False 1656 ) 1657 1658 ### Determine if the package exists. 1659 if precheck is False: 1660 found_module = ( 1661 do_import( 1662 name, debug=debug, warn=False, venv=venv, color=color, 1663 check_update=False, check_pypi=False, split=split, 1664 ) is not None 1665 ) 1666 else: 1667 installed_cache_key = (name, venv, split, allow_outside_venv) 1668 if check_is_installed: 1669 with _locks['_is_installed_first_check']: 1670 if not _is_installed_first_check.get(installed_cache_key, False): 1671 package_is_installed = is_installed( 1672 name, 1673 venv = venv, 1674 split = split, 1675 allow_outside_venv = allow_outside_venv, 1676 debug = debug, 1677 ) 1678 if package_is_installed: 1679 _is_installed_first_check[installed_cache_key] = True 1680 else: 1681 package_is_installed = True 1682 else: 1683 package_is_installed = venv_contains_package( 1684 name, 1685 venv=venv, 1686 split=split, 1687 debug=debug, 1688 ) 1689 found_module = package_is_installed 1690 1691 if not found_module: 1692 if install: 1693 with _locks['emitted_auto_install_warning']: 1694 if warn and not emitted_auto_install_warning: 1695 emitted_auto_install_warning = True 1696 warn_function( 1697 "Meerschaum is installing a missing runtime dependency. " 1698 + f"Set {no_auto_install_env_var}=1 to disable automatic downloads.", 1699 ImportWarning, 1700 stacklevel=3, 1701 color=False, 1702 ) 1703 if not pip_install( 1704 install_name, 1705 venv = venv, 1706 split = False, 1707 check_update = check_update, 1708 color = color, 1709 debug = debug, 1710 _implicit = True, 1711 ): 1712 if warn: 1713 warn_function( 1714 f"Failed to install '{install_name}'.", 1715 ImportWarning, 1716 stacklevel = 3, 1717 color = False, 1718 ) 1719 else: 1720 _record_import_request(install_name, venv) 1721 elif warn: 1722 ### Raise a warning if we can't find the package and install = False. 1723 warn_function( 1724 (f"\n\nMissing package '{name}' from virtual environment '{venv}'; " 1725 + "some features will not work correctly." 1726 + ( 1727 f"\n\nUnset {no_auto_install_env_var} to allow package installation.\n" 1728 if no_auto_install_env_var in os.environ 1729 else "\n\nSet install=True when calling attempt_import.\n" 1730 )), 1731 ImportWarning, 1732 stacklevel = 3, 1733 color = False, 1734 ) 1735 1736 elif found_module: 1737 _record_import_request(install_name, venv, only_plugins=True) 1738 1739 ### Do the import. Will be lazy if lazy=True. 1740 m = do_import( 1741 name, debug=debug, warn=warn, venv=venv, color=color, 1742 check_update=check_update, check_pypi=check_pypi, install=install, split=split, 1743 ) 1744 modules.append(m) 1745 1746 modules = tuple(modules) 1747 if len(modules) == 1: 1748 return modules[0] 1749 return modules 1750 1751 1752def _update_request_ledger(install_names: List[str], venv: Optional[str], uninstall: bool) -> None: 1753 """ 1754 Keep `venvs/<venv>/.mrsm_requests.json` in step with a successful `pip_install()` (D20): 1755 record the caller (a plugin, else `meerschaum`) for installs, forget uninstalled packages. 1756 """ 1757 if venv is None: 1758 return 1759 try: 1760 from meerschaum.utils.venv import _requests 1761 if uninstall: 1762 _requests.forget_requests(venv, install_names) 1763 return 1764 requester = _requests.get_requester() 1765 for install_name in install_names: 1766 if install_name.startswith(('-', '/', '.')) or '://' in install_name: 1767 continue 1768 _requests.record_request(venv, install_name, requester) 1769 except Exception: 1770 pass 1771 1772 1773def _record_import_request( 1774 install_name: str, 1775 venv: Optional[str], 1776 only_plugins: bool = False, 1777) -> None: 1778 """ 1779 Record in `venvs/<venv>/.mrsm_requests.json` who asked for `install_name` (D20). 1780 With `only_plugins`, requests by Meerschaum itself are not recorded 1781 (used for packages that are already installed). 1782 """ 1783 try: 1784 from meerschaum.utils.venv._requests import record_request, get_requester, CORE_REQUESTER 1785 requester = get_requester() 1786 if only_plugins and requester == CORE_REQUESTER: 1787 return 1788 record_request(venv, install_name, requester) 1789 except Exception: 1790 pass 1791 1792 1793def lazy_import( 1794 name: str, 1795 local_name: str = None, 1796 **kw 1797) -> meerschaum.utils.packages.lazy_loader.LazyLoader: 1798 """ 1799 Lazily import a package. 1800 """ 1801 from meerschaum.utils.packages.lazy_loader import LazyLoader 1802 if local_name is None: 1803 local_name = name 1804 return LazyLoader( 1805 local_name, 1806 globals(), 1807 name, 1808 **kw 1809 ) 1810 1811 1812def pandas_name() -> str: 1813 """ 1814 Return the configured name for `pandas`. 1815 1816 Below are the expected possible values: 1817 1818 - 'pandas' 1819 - 'modin.pandas' 1820 - 'dask.dataframe' 1821 1822 """ 1823 from meerschaum.config import get_config 1824 pandas_module_name = get_config('system', 'connectors', 'all', 'pandas', patch=True) 1825 if pandas_module_name == 'modin': 1826 pandas_module_name = 'modin.pandas' 1827 elif pandas_module_name == 'dask': 1828 pandas_module_name = 'dask.dataframe' 1829 1830 return pandas_module_name 1831 1832 1833emitted_pandas_warning: bool = False 1834def import_pandas( 1835 debug: bool = False, 1836 lazy: bool = False, 1837 **kw 1838) -> 'ModuleType': 1839 """ 1840 Quality-of-life function to attempt to import the configured version of `pandas`. 1841 """ 1842 pandas_module_name = pandas_name() 1843 global emitted_pandas_warning 1844 1845 if pandas_module_name != 'pandas': 1846 with _locks['emitted_pandas_warning']: 1847 if not emitted_pandas_warning: 1848 from meerschaum.utils.warnings import warn 1849 emitted_pandas_warning = True 1850 warn( 1851 ( 1852 "You are using an alternative Pandas implementation " 1853 + f"'{pandas_module_name}'" 1854 + "\n Features may not work as expected." 1855 ), 1856 stack=False, 1857 ) 1858 1859 pandas, pyarrow = attempt_import('pandas', 'pyarrow', debug=debug, lazy=False, **kw) 1860 pd = attempt_import(pandas_module_name, debug=debug, lazy=lazy, **kw) 1861 _warn_if_pandas_is_too_old(pandas) 1862 return pd 1863 1864 1865_emitted_old_pandas_warning = False 1866 1867 1868def _warn_if_pandas_is_too_old(pandas: Any) -> None: 1869 """Warn once per process that the installed pandas is older than the `pandas` extra's.""" 1870 global _emitted_old_pandas_warning 1871 version = getattr(pandas, '__version__', None) 1872 if _emitted_old_pandas_warning or not version: 1873 return 1874 from meerschaum.utils.packages._packages import all_packages 1875 required = (all_packages.get('pandas', 'pandas>=3.0.0').split(']')[-1]).strip() 1876 if _version_satisfies(version, required) is not False: 1877 return 1878 _emitted_old_pandas_warning = True 1879 from meerschaum.utils.warnings import warn 1880 warn( 1881 f"The installed pandas {version} is older than the {required} Meerschaum requires: " 1882 "results (dtypes, datetime units) may differ. Upgrade it with " 1883 "`mrsm upgrade packages pandas`.", 1884 stack=False, 1885 ) 1886 1887 1888def import_rich( 1889 lazy: bool = True, 1890 debug: bool = False, 1891 **kw: Any 1892) -> 'ModuleType': 1893 """ 1894 Quality of life function for importing `rich`. 1895 """ 1896 from meerschaum.utils.formatting import ANSI, UNICODE 1897 ## need typing_extensions for `from rich import box` 1898 typing_extensions = attempt_import( 1899 'typing_extensions', lazy=False, debug=debug 1900 ) 1901 pygments = attempt_import( 1902 'pygments', lazy=False, 1903 ) 1904 rich = attempt_import( 1905 'rich', lazy=lazy, 1906 **kw 1907 ) 1908 return rich 1909 1910 1911def _dash_less_than_2(**kw) -> bool: 1912 dash = attempt_import('dash', **kw) 1913 if dash is None: 1914 return None 1915 packaging_version = attempt_import('packaging.version', **kw) 1916 return ( 1917 packaging_version.parse(dash.__version__) < 1918 packaging_version.parse('2.0.0') 1919 ) 1920 1921 1922def import_dcc(warn=False, **kw) -> 'ModuleType': 1923 """ 1924 Import Dash Core Components (`dcc`). 1925 """ 1926 return ( 1927 attempt_import('dash_core_components', warn=warn, **kw) 1928 if _dash_less_than_2(warn=warn, **kw) else attempt_import('dash.dcc', warn=warn, **kw) 1929 ) 1930 1931 1932def import_html(warn=False, **kw) -> 'ModuleType': 1933 """ 1934 Import Dash HTML Components (`html`). 1935 """ 1936 return ( 1937 attempt_import('dash_html_components', warn=warn, **kw) 1938 if _dash_less_than_2(warn=warn, **kw) 1939 else attempt_import('dash.html', warn=warn, **kw) 1940 ) 1941 1942 1943def get_modules_from_package( 1944 package: Any, 1945 names: bool = False, 1946 recursive: bool = False, 1947 lazy: bool = False, 1948 modules_venvs: bool = False, 1949 debug: bool = False 1950): 1951 """ 1952 Find and import all modules in a package. 1953 1954 Returns 1955 ------- 1956 Either list of modules or tuple of lists. 1957 """ 1958 from os.path import dirname, join, isfile, isdir, basename 1959 import glob 1960 1961 pattern = '*' if recursive else '*.py' 1962 package_path = dirname(package.__file__ or package.__path__[0]) 1963 module_names = glob.glob(join(package_path, pattern), recursive=recursive) 1964 _all = [ 1965 basename(f)[:-3] if isfile(f) else basename(f) 1966 for f in module_names 1967 if ((isfile(f) and f.endswith('.py')) or isdir(f)) 1968 and not f.endswith('__init__.py') 1969 and not f.endswith('__pycache__') 1970 ] 1971 ### 5.1: in an isolated team's sandboxed process the plugins package holds every team's 1972 ### links, but only the team's own plugins can be read. 1973 if package.__name__ == 'plugins': 1974 from meerschaum.plugins import sandboxed_plugins_names 1975 own = sandboxed_plugins_names() 1976 if own is not None: 1977 _all = [name for name in _all if name in own] 1978 1979 if debug: 1980 from meerschaum.utils.debug import dprint 1981 dprint(str(_all)) 1982 modules = [] 1983 for module_name in [package.__name__ + "." + mod_name for mod_name in _all]: 1984 ### there's probably a better way than a try: catch but it'll do for now 1985 try: 1986 ### if specified, activate the module's virtual environment before importing. 1987 ### NOTE: this only considers the filename, so two modules from different packages 1988 ### may end up sharing virtual environments. 1989 if modules_venvs: 1990 activate_venv(module_name.split('.')[-1], debug=debug) 1991 m = lazy_import(module_name, debug=debug) if lazy else _import_module(module_name) 1992 modules.append(m) 1993 except Exception: 1994 import traceback 1995 traceback.print_exc() 1996 finally: 1997 if modules_venvs: 1998 deactivate_venv(module_name.split('.')[-1], debug=debug) 1999 if names: 2000 return _all, modules 2001 2002 return modules 2003 2004 2005def import_children( 2006 package: Optional['ModuleType'] = None, 2007 package_name: Optional[str] = None, 2008 types : Optional[List[str]] = None, 2009 lazy: bool = True, 2010 recursive: bool = False, 2011 debug: bool = False 2012) -> List['ModuleType']: 2013 """ 2014 Import all functions in a package to its `__init__`. 2015 2016 Parameters 2017 ---------- 2018 package: Optional[ModuleType], default None 2019 Package to import its functions into. 2020 If `None` (default), use parent. 2021 2022 package_name: Optional[str], default None 2023 Name of package to import its functions into 2024 If None (default), use parent. 2025 2026 types: Optional[List[str]], default None 2027 Types of members to return. 2028 Defaults are `['method', 'builtin', 'class', 'function', 'package', 'module']` 2029 2030 Returns 2031 ------- 2032 A list of modules. 2033 """ 2034 import sys, inspect 2035 2036 if types is None: 2037 types = ['method', 'builtin', 'function', 'class', 'module'] 2038 2039 ### if package_name and package are None, use parent 2040 if package is None and package_name is None: 2041 package_name = inspect.stack()[1][0].f_globals['__name__'] 2042 2043 ### populate package or package_name from other other 2044 if package is None: 2045 package = sys.modules[package_name] 2046 elif package_name is None: 2047 package_name = package.__name__ 2048 2049 ### Set attributes in sys module version of package. 2050 ### Kinda like setting a dictionary 2051 ### functions[name] = func 2052 modules = get_modules_from_package(package, recursive=recursive, lazy=lazy, debug=debug) 2053 _all, members = [], [] 2054 objects = [] 2055 for module in modules: 2056 _objects = [] 2057 for ob in inspect.getmembers(module): 2058 for t in types: 2059 ### ob is a tuple of (name, object) 2060 if getattr(inspect, 'is' + t)(ob[1]): 2061 _objects.append(ob) 2062 2063 if 'module' in types: 2064 _objects.append((module.__name__.split('.')[0], module)) 2065 objects += _objects 2066 for ob in objects: 2067 setattr(sys.modules[package_name], ob[0], ob[1]) 2068 _all.append(ob[0]) 2069 members.append(ob[1]) 2070 2071 if debug: 2072 from meerschaum.utils.debug import dprint 2073 dprint(str(_all)) 2074 ### set __all__ for import * 2075 setattr(sys.modules[package_name], '__all__', _all) 2076 return members 2077 2078 2079_reload_module_cache = {} 2080def reload_package( 2081 package: str, 2082 skip_submodules: Optional[List[str]] = None, 2083 lazy: bool = False, 2084 debug: bool = False, 2085 **kw: Any 2086): 2087 """ 2088 Recursively load a package's subpackages, even if they were not previously loaded. 2089 """ 2090 import sys 2091 if isinstance(package, str): 2092 package_name = package 2093 else: 2094 try: 2095 package_name = package.__name__ 2096 except Exception as e: 2097 package_name = str(package) 2098 2099 skip_submodules = skip_submodules or [] 2100 if 'meerschaum.utils.packages' not in skip_submodules: 2101 skip_submodules.append('meerschaum.utils.packages') 2102 def safeimport(): 2103 subs = [ 2104 m for m in sys.modules 2105 if m.startswith(package_name + '.') 2106 ] 2107 subs_to_skip = [] 2108 for skip_mod in skip_submodules: 2109 for mod in subs: 2110 if mod.startswith(skip_mod): 2111 subs_to_skip.append(mod) 2112 continue 2113 2114 subs = [m for m in subs if m not in subs_to_skip] 2115 for module_name in subs: 2116 _reload_module_cache[module_name] = sys.modules.pop(module_name, None) 2117 if not subs_to_skip: 2118 _reload_module_cache[package_name] = sys.modules.pop(package_name, None) 2119 2120 return _import_module(package_name) 2121 2122 return safeimport() 2123 2124 2125def reload_meerschaum(debug: bool = False) -> SuccessTuple: 2126 """ 2127 Reload the currently loaded Meercshaum modules, refreshing plugins. 2128 """ 2129 reload_package( 2130 'meerschaum', 2131 skip_submodules = [ 2132 'meerschaum.utils.pool', 2133 ] 2134 ) 2135 2136 from meerschaum.plugins import reload_plugins 2137 reload_plugins(debug=debug) 2138 return True, "Success" 2139 2140 2141def is_installed( 2142 import_name: str, 2143 venv: Optional[str] = 'mrsm', 2144 split: bool = True, 2145 allow_outside_venv: bool = True, 2146 debug: bool = False, 2147) -> bool: 2148 """ 2149 Check whether a package is installed. 2150 2151 Parameters 2152 ---------- 2153 import_name: str 2154 The import name of the module. 2155 2156 venv: Optional[str], default 'mrsm' 2157 The venv in which to search for the module. 2158 2159 split: bool, default True 2160 If `True`, split on periods to determine the root module name. 2161 2162 allow_outside_venv: bool, default True 2163 If `True`, search outside of the specified virtual environment 2164 if the package cannot be found. 2165 2166 Returns 2167 ------- 2168 A bool indicating whether a package may be imported. 2169 """ 2170 if debug: 2171 from meerschaum.utils.debug import dprint 2172 root_name = import_name.split('.')[0] if split else import_name 2173 import importlib.util 2174 with Venv(venv, debug=debug): 2175 try: 2176 spec_path = pathlib.Path( 2177 get_module_path(root_name, venv=venv, debug=debug) 2178 or 2179 ( 2180 importlib.util.find_spec(root_name).origin 2181 if venv is not None and allow_outside_venv 2182 else None 2183 ) 2184 ) 2185 except (ModuleNotFoundError, ValueError, AttributeError, TypeError) as e: 2186 spec_path = None 2187 2188 ### Whether the package is present, not whether it meets Meerschaum's minimum version: 2189 ### a too-old package is reported (`import_pandas()`, `attempt_import(check_update=True)`), 2190 ### never replaced by an implicit install. 2191 found = spec_path is not None 2192 2193 return found 2194 2195 2196def venv_contains_package( 2197 import_name: str, 2198 venv: Optional[str] = 'mrsm', 2199 split: bool = True, 2200 debug: bool = False, 2201) -> bool: 2202 """ 2203 Search the contents of a virtual environment for a package. 2204 """ 2205 import site 2206 import pathlib 2207 root_name = import_name.split('.')[0] if split else import_name 2208 return get_module_path(root_name, venv=venv, debug=debug) is not None 2209 2210 2211def package_venv(package: 'ModuleType') -> Union[str, None]: 2212 """ 2213 Inspect a package and return the virtual environment in which it presides. 2214 """ 2215 import os 2216 import meerschaum.config.paths as paths 2217 if str(paths.VIRTENV_RESOURCES_PATH) not in package.__file__: 2218 return None 2219 return package.__file__.split(str(paths.VIRTENV_RESOURCES_PATH))[1].split(os.path.sep)[1] 2220 2221 2222def ensure_readline() -> 'ModuleType': 2223 """Make sure that the `readline` package is able to be imported.""" 2224 import sys 2225 try: 2226 import readline 2227 except ImportError: 2228 readline = None 2229 2230 if readline is None: 2231 import platform 2232 rl_name = "gnureadline" if platform.system() != 'Windows' else "pyreadline3" 2233 try: 2234 rl = attempt_import( 2235 rl_name, 2236 lazy=False, 2237 install=True, 2238 venv=None, 2239 warn=False, 2240 ) 2241 except (ImportError, ModuleNotFoundError): 2242 if not pip_install( 2243 rl_name, 2244 args=['--upgrade', '--ignore-installed'], 2245 venv=None, 2246 _implicit=True, 2247 ): 2248 print(f"Unable to import {rl_name}!", file=sys.stderr) 2249 sys.exit(1) 2250 2251 sys.modules['readline'] = readline 2252 return readline 2253 2254 2255def _get_pip_os_env(color: bool = True): 2256 """ 2257 Return the environment variables context in which `pip` should be run. 2258 See PEP 668 for why we are overriding the environment. 2259 """ 2260 import os, sys, platform 2261 from meerschaum.config.environment import get_child_env 2262 python_bin_path = pathlib.Path(sys.executable) 2263 pip_os_env = get_child_env() 2264 path_str = pip_os_env.get('PATH', '') or '' 2265 path_sep = ':' if platform.system() != 'Windows' else ';' 2266 pip_os_env.update({ 2267 'PIP_BREAK_SYSTEM_PACKAGES': 'true', 2268 'UV_BREAK_SYSTEM_PACKAGES': 'true', 2269 # Venv targets contain packages imported by this Python process. Resolve wheels 2270 # for its ABI even when uv discovers a project venv or inherits UV_PYTHON. 2271 'UV_PYTHON': sys.executable, 2272 ('FORCE_COLOR' if color else 'NO_COLOR'): '1', 2273 }) 2274 if str(python_bin_path) not in path_str: 2275 pip_os_env['PATH'] = str(python_bin_path.parent) + path_sep + path_str 2276 2277 return pip_os_env 2278 2279 2280def use_uv() -> bool: 2281 """ 2282 Return whether `uv` is available and enabled. 2283 """ 2284 from meerschaum.utils.misc import is_android 2285 if is_android(): 2286 return False 2287 2288 if not is_uv_enabled(): 2289 return False 2290 2291 return _get_uv_bin() is not None 2292 2293 2294def is_uv_enabled() -> bool: 2295 """ 2296 Return whether the user has disabled `uv`. 2297 """ 2298 from meerschaum.utils.misc import is_android 2299 if is_android(): 2300 return False 2301 2302 from meerschaum.config import get_config 2303 enabled = get_config('system', 'experimental', 'uv_pip') 2304 return enabled
99def get_pip_install_lock_path(venv: Optional[str] = 'mrsm') -> pathlib.Path: 100 """Return the cross-process package installation lock path for an environment.""" 101 import hashlib 102 import tempfile 103 target_path = _get_pip_install_target_path(venv).resolve() 104 target_key = os.path.normcase(str(target_path)) 105 target_hash = hashlib.sha256(target_key.encode('utf-8')).hexdigest()[:16] 106 return ( 107 pathlib.Path(tempfile.gettempdir()) 108 / 'meerschaum-package-installs' 109 / (target_hash + '.lock') 110 )
Return the cross-process package installation lock path for an environment.
163def get_module_path( 164 import_name: str, 165 venv: Optional[str] = 'mrsm', 166 debug: bool = False, 167 _try_install_name_on_fail: bool = True, 168) -> Union[pathlib.Path, None]: 169 """ 170 Get a module's path without importing. 171 """ 172 import site 173 if debug: 174 from meerschaum.utils.debug import dprint 175 if not _try_install_name_on_fail: 176 install_name = _import_to_install_name(import_name, with_version=False) 177 install_name_lower = install_name.lower().replace('-', '_') 178 import_name_lower = install_name_lower 179 else: 180 import_name_lower = import_name.lower().replace('-', '_') 181 182 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 183 if not vtp.exists(): 184 if debug: 185 dprint( 186 ( 187 "Venv '{venv}' does not exist, cannot import " 188 + f"'{import_name}'." 189 ), 190 color = False, 191 ) 192 return None 193 194 venv_target_candidate_paths = [vtp] 195 if venv is None: 196 site_user_packages_dirs = [ 197 pathlib.Path(site.getusersitepackages()) 198 ] if not inside_venv() else [] 199 site_packages_dirs = [pathlib.Path(path) for path in site.getsitepackages()] 200 201 paths_to_add = [ 202 path 203 for path in site_user_packages_dirs + site_packages_dirs 204 if path not in venv_target_candidate_paths 205 ] 206 venv_target_candidate_paths += paths_to_add 207 208 candidates = [] 209 for venv_target_candidate in venv_target_candidate_paths: 210 try: 211 file_names = os.listdir(venv_target_candidate) 212 except FileNotFoundError: 213 continue 214 for file_name in file_names: 215 file_name_lower = file_name.lower().replace('-', '_') 216 if not file_name_lower.startswith(import_name_lower): 217 continue 218 if file_name.endswith('dist_info'): 219 continue 220 file_path = venv_target_candidate / file_name 221 222 ### Most likely: Is a directory with __init__.py 223 if file_name_lower == import_name_lower and file_path.is_dir(): 224 init_path = file_path / '__init__.py' 225 if init_path.exists(): 226 candidates.append(init_path) 227 228 ### May be a standalone .py file. 229 elif file_name_lower == import_name_lower + '.py': 230 candidates.append(file_path) 231 232 ### Compiled wheels (e.g. pyodbc) 233 elif file_name_lower.startswith(import_name_lower + '.'): 234 candidates.append(file_path) 235 236 if len(candidates) == 1: 237 return candidates[0] 238 239 if not candidates: 240 if _try_install_name_on_fail: 241 return get_module_path( 242 import_name, venv=venv, debug=debug, 243 _try_install_name_on_fail=False 244 ) 245 return None 246 247 specs_paths = [] 248 for candidate_path in candidates: 249 spec = importlib.util.spec_from_file_location(import_name, str(candidate_path)) 250 if spec is not None: 251 return candidate_path 252 253 return None
Get a module's path without importing.
256def manually_import_module( 257 import_name: str, 258 venv: Optional[str] = 'mrsm', 259 check_update: bool = True, 260 check_pypi: bool = False, 261 install: bool = True, 262 split: bool = True, 263 warn: bool = True, 264 color: bool = True, 265 debug: bool = False, 266 use_sys_modules: bool = True, 267) -> Union['ModuleType', None]: 268 """ 269 Manually import a module from a virtual environment (or the base environment). 270 271 Parameters 272 ---------- 273 import_name: str 274 The name of the module. 275 276 venv: Optional[str], default 'mrsm' 277 The virtual environment to read from. 278 279 check_update: bool, default True 280 If `True`, examine whether the available version of the package meets the required version. 281 282 check_pypi: bool, default False 283 If `True`, check PyPI for updates before importing. 284 285 install: bool, default True 286 If `True`, install the package if it's not installed or needs an update. 287 288 split: bool, default True 289 If `True`, split `import_name` on periods to get the package name. 290 291 warn: bool, default True 292 If `True`, raise a warning if the package cannot be imported. 293 294 color: bool, default True 295 If `True`, use color output for debug and warning text. 296 297 debug: bool, default False 298 Verbosity toggle. 299 300 use_sys_modules: bool, default True 301 If `True`, return the module in `sys.modules` if it exists. 302 Otherwise continue with manually importing. 303 304 Returns 305 ------- 306 The specified module or `None` if it can't be imported. 307 308 """ 309 import sys 310 _previously_imported = import_name in sys.modules 311 if _previously_imported and use_sys_modules: 312 return sys.modules[import_name] 313 314 from meerschaum.utils.warnings import warn as warn_function 315 import warnings 316 root_name = import_name.split('.')[0] if split else import_name 317 install_name = _import_to_install_name(root_name) 318 319 root_path = get_module_path(root_name, venv=venv) 320 if root_path is None: 321 return None 322 323 mod_path = root_path 324 if mod_path.is_dir(): 325 for _dir in import_name.split('.')[:-1]: 326 mod_path = mod_path / _dir 327 possible_end_module_filename = import_name.split('.')[-1] + '.py' 328 try: 329 mod_path = ( 330 (mod_path / possible_end_module_filename) 331 if possible_end_module_filename in os.listdir(mod_path) 332 else ( 333 mod_path / import_name.split('.')[-1] / '__init__.py' 334 ) 335 ) 336 except Exception: 337 mod_path = None 338 339 spec = ( 340 importlib.util.find_spec(import_name) 341 if mod_path is None or not mod_path.exists() 342 else importlib.util.spec_from_file_location(import_name, str(mod_path)) 343 ) 344 root_spec = ( 345 importlib.util.find_spec(root_name) 346 if not root_path.exists() 347 else importlib.util.spec_from_file_location(root_name, str(root_path)) 348 ) 349 350 ### Check for updates before importing. 351 _version = ( 352 determine_version( 353 pathlib.Path(root_spec.origin), 354 import_name=root_name, venv=venv, debug=debug 355 ) if root_spec is not None and root_spec.origin is not None else None 356 ) 357 358 if _version is not None: 359 if check_update: 360 if need_update( 361 None, 362 import_name=root_name, 363 version=_version, 364 check_pypi=check_pypi, 365 debug=debug, 366 ): 367 ### An installed package that is too old (or has a newer release) is never 368 ### replaced behind the user's back: say how to upgrade it. 369 if warn: 370 warn_function( 371 f"The installed '{root_name}' ({_version}) is older than what is " 372 f"required or available. Upgrade it with `mrsm upgrade packages " 373 f"{root_name}`.", 374 stack=False, 375 color=False, 376 ) 377 spec = ( 378 importlib.util.find_spec(import_name) 379 if mod_path is None or not mod_path.exists() 380 else importlib.util.spec_from_file_location(import_name, str(mod_path)) 381 ) 382 383 if spec is None: 384 try: 385 mod = _import_module(import_name) 386 except Exception: 387 mod = None 388 return mod 389 390 with Venv(venv, debug=debug): 391 mod = importlib.util.module_from_spec(spec) 392 old_sys_mod = sys.modules.get(import_name, None) 393 sys.modules[import_name] = mod 394 395 try: 396 with warnings.catch_warnings(): 397 warnings.filterwarnings('ignore', 'The NumPy') 398 spec.loader.exec_module(mod) 399 except Exception: 400 pass 401 mod = _import_module(import_name) 402 if old_sys_mod is not None: 403 sys.modules[import_name] = old_sys_mod 404 else: 405 del sys.modules[import_name] 406 407 return mod
Manually import a module from a virtual environment (or the base environment).
Parameters
- import_name (str): The name of the module.
- venv (Optional[str], default 'mrsm'): The virtual environment to read from.
- check_update (bool, default True):
If
True, examine whether the available version of the package meets the required version. - check_pypi (bool, default False):
If
True, check PyPI for updates before importing. - install (bool, default True):
If
True, install the package if it's not installed or needs an update. - split (bool, default True):
If
True, splitimport_nameon periods to get the package name. - warn (bool, default True):
If
True, raise a warning if the package cannot be imported. - color (bool, default True):
If
True, use color output for debug and warning text. - debug (bool, default False): Verbosity toggle.
- use_sys_modules (bool, default True):
If
True, return the module insys.modulesif it exists. Otherwise continue with manually importing.
Returns
- The specified module or
Noneif it can't be imported.
438def get_install_no_version(install_name: str) -> str: 439 """ 440 Strip the version information from the install name. 441 """ 442 import re 443 return re.split(r'[\[=<>,! \]]', install_name)[0]
Strip the version information from the install name.
447def determine_version( 448 path: pathlib.Path, 449 import_name: Optional[str] = None, 450 venv: Optional[str] = 'mrsm', 451 search_for_metadata: bool = True, 452 split: bool = True, 453 warn: bool = False, 454 debug: bool = False, 455) -> Union[str, None]: 456 """ 457 Determine a module's `__version__` string from its filepath. 458 459 First it searches for pip metadata, then it attempts to import the module in a subprocess. 460 461 Parameters 462 ---------- 463 path: pathlib.Path 464 The file path of the module. 465 466 import_name: Optional[str], default None 467 The name of the module. If omitted, it will be determined from the file path. 468 Defaults to `None`. 469 470 venv: Optional[str], default 'mrsm' 471 The virtual environment of the Python interpreter to use if importing is necessary. 472 473 search_for_metadata: bool, default True 474 If `True`, search the pip site_packages directory (assumed to be the parent) 475 for the corresponding dist-info directory. 476 477 warn: bool, default True 478 If `True`, raise a warning if the module fails to import in the subprocess. 479 480 split: bool, default True 481 If `True`, split the determined import name by periods to get the room name. 482 483 Returns 484 ------- 485 The package's version string if available or `None`. 486 If multiple versions are found, it will trigger an import in a subprocess. 487 488 """ 489 with _locks['import_versions']: 490 if venv not in import_versions: 491 import_versions[venv] = {} 492 import os 493 old_cwd = os.getcwd() 494 from meerschaum.utils.warnings import warn as warn_function 495 if import_name is None: 496 import_name = path.parent.stem if path.stem == '__init__' else path.stem 497 import_name = import_name.split('.')[0] if split else import_name 498 if import_name in import_versions[venv]: 499 return import_versions[venv][import_name] 500 _version = None 501 module_parent_dir = ( 502 path.parent.parent if path.stem == '__init__' else path.parent 503 ) if path is not None else venv_target_path(venv, allow_nonexistent=True, debug=debug) 504 505 if not module_parent_dir.exists(): 506 return None 507 508 installed_dir_name = _import_to_dir_name(import_name) 509 clean_installed_dir_name = installed_dir_name.lower().replace('-', '_') 510 511 ### First, check if a dist-info directory exists. 512 _found_versions = [] 513 if search_for_metadata: 514 try: 515 filenames = os.listdir(module_parent_dir) 516 except FileNotFoundError: 517 filenames = [] 518 for filename in filenames: 519 if not filename.endswith('.dist-info'): 520 continue 521 filename_lower = filename.lower() 522 if not filename_lower.startswith(clean_installed_dir_name + '-'): 523 continue 524 _v = filename.replace('.dist-info', '').split("-")[-1] 525 _found_versions.append(_v) 526 527 if len(_found_versions) == 1: 528 _version = _found_versions[0] 529 with _locks['import_versions']: 530 import_versions[venv][import_name] = _version 531 return _found_versions[0] 532 533 if not _found_versions: 534 try: 535 import importlib.metadata as importlib_metadata 536 except ImportError: 537 importlib_metadata = attempt_import( 538 'importlib_metadata', 539 debug=debug, check_update=False, precheck=False, 540 color=False, check_is_installed=False, lazy=False, 541 ) 542 try: 543 os.chdir(module_parent_dir) 544 _version = importlib_metadata.metadata(import_name)['Version'] 545 except Exception: 546 _version = None 547 finally: 548 os.chdir(old_cwd) 549 550 if _version is not None: 551 with _locks['import_versions']: 552 import_versions[venv][import_name] = _version 553 return _version 554 555 if debug: 556 print(f'Found multiple versions for {import_name}: {_found_versions}') 557 558 module_parent_dir_str = module_parent_dir.as_posix() 559 560 ### Not a pip package, so let's try importing the module directly (in a subprocess). 561 _no_version_str = 'no-version' 562 code = ( 563 f"import sys, importlib; sys.path.insert(0, '{module_parent_dir_str}');\n" 564 + f"module = importlib.import_module('{import_name}');\n" 565 + "try:\n" 566 + " print(module.__version__ , end='')\n" 567 + "except:\n" 568 + f" print('{_no_version_str}', end='')" 569 ) 570 from meerschaum.config.environment import get_child_env 571 exit_code, stdout_bytes, stderr_bytes = venv_exec( 572 code, venv=venv, with_extras=True, env=get_child_env(), debug=debug 573 ) 574 stdout, stderr = stdout_bytes.decode('utf-8'), stderr_bytes.decode('utf-8') 575 _version = stdout.split('\n')[-1] if exit_code == 0 else None 576 _version = _version if _version != _no_version_str else None 577 578 if _version is None: 579 _version = _get_package_metadata(import_name, venv).get('version', None) 580 if _version is None and warn: 581 warn_function( 582 f"Failed to determine a version for '{import_name}':\n{stderr}", 583 stack = False 584 ) 585 586 ### If `__version__` doesn't exist, return `None`. 587 import_versions[venv][import_name] = _version 588 return _version
Determine a module's __version__ string from its filepath.
First it searches for pip metadata, then it attempts to import the module in a subprocess.
Parameters
- path (pathlib.Path): The file path of the module.
- import_name (Optional[str], default None):
The name of the module. If omitted, it will be determined from the file path.
Defaults to
None. - venv (Optional[str], default 'mrsm'): The virtual environment of the Python interpreter to use if importing is necessary.
- search_for_metadata (bool, default True):
If
True, search the pip site_packages directory (assumed to be the parent) for the corresponding dist-info directory. - warn (bool, default True):
If
True, raise a warning if the module fails to import in the subprocess. - split (bool, default True):
If
True, split the determined import name by periods to get the room name.
Returns
- The package's version string if available or
None. - If multiple versions are found, it will trigger an import in a subprocess.
683def need_update( 684 package: Optional['ModuleType'] = None, 685 install_name: Optional[str] = None, 686 import_name: Optional[str] = None, 687 version: Optional[str] = None, 688 check_pypi: bool = False, 689 split: bool = True, 690 color: bool = True, 691 debug: bool = False, 692 _run_determine_version: bool = True, 693) -> bool: 694 """ 695 Check if a Meerschaum dependency needs an update. 696 Returns a bool for whether or not a package needs to be updated. 697 698 Parameters 699 ---------- 700 package: 'ModuleType' 701 The module of the package to be updated. 702 703 install_name: Optional[str], default None 704 If provided, use this string to determine the required version. 705 Otherwise use the install name defined in `meerschaum.utils.packages._packages`. 706 707 import_name: 708 If provided, override the package's `__name__` string. 709 710 version: Optional[str], default None 711 If specified, override the package's `__version__` string. 712 713 check_pypi: bool, default False 714 If `True`, check pypi.org for updates. 715 Defaults to `False`. 716 717 split: bool, default True 718 If `True`, split the module's name on periods to detrive the root name. 719 Defaults to `True`. 720 721 color: bool, default True 722 If `True`, format debug output. 723 Defaults to `True`. 724 725 debug: bool, default True 726 Verbosity toggle. 727 728 Returns 729 ------- 730 A bool indicating whether the package requires an update. 731 732 """ 733 if debug: 734 from meerschaum.utils.debug import dprint 735 from meerschaum.utils.warnings import warn as warn_function 736 import re 737 root_name = ( 738 package.__name__.split('.')[0] if split else package.__name__ 739 ) if import_name is None else ( 740 import_name.split('.')[0] if split else import_name 741 ) 742 install_name = install_name or _import_to_install_name(root_name) 743 auto_install_allowed = _auto_install_allowed() 744 ### Asking PyPI for the latest release is an implicit network request. 745 check_pypi = check_pypi and auto_install_allowed 746 with _locks['_checked_for_updates']: 747 if install_name in _checked_for_updates: 748 return False 749 _checked_for_updates.add(install_name) 750 751 _install_no_version = get_install_no_version(install_name) 752 required_version = ( 753 install_name 754 .replace(_install_no_version, '') 755 ) 756 if ']' in required_version: 757 required_version = required_version.split(']')[1] 758 759 ### No minimum version was specified, and we're not going to check PyPI. 760 if not required_version and not check_pypi: 761 return False 762 763 ### NOTE: Sometimes (rarely), we depend on a development build of a package. 764 if '.dev' in required_version: 765 required_version = required_version.split('.dev')[0] 766 if version and '.dev' in version: 767 version = version.split('.dev')[0] 768 769 try: 770 if not version: 771 if not _run_determine_version: 772 version = determine_version( 773 pathlib.Path(package.__file__), 774 import_name=root_name, warn=False, debug=debug 775 ) 776 if version is None: 777 return False 778 except Exception as e: 779 if debug: 780 dprint(str(e), color=color) 781 dprint("No version could be determined from the installed package.", color=color) 782 return False 783 raw_version = version 784 split_version = version.split('.') 785 last_part = split_version[-1] 786 if len(split_version) == 2: 787 version = '.'.join(split_version) + '.0' 788 elif 'dev' in last_part or 'rc' in last_part: 789 tag = 'dev' if 'dev' in last_part else 'rc' 790 last_sep = '-' 791 if not last_part.startswith(tag): 792 last_part = f'-{tag}'.join(last_part.split(tag)) 793 last_sep = '.' 794 version = '.'.join(split_version[:-1]) + last_sep + last_part 795 elif len(split_version) > 3: 796 version = '.'.join(split_version[:3]) 797 798 if check_pypi: 799 ### Check PyPI for updates 800 update_checker, packaging_version = attempt_import( 801 'update_checker', 'packaging.version', lazy=False, check_update=False, debug=debug 802 ) 803 checker = update_checker.UpdateChecker() 804 result = checker.check(_install_no_version, version) 805 else: 806 ### Skip PyPI and assume we can't be sure. 807 result = None 808 809 ### Compare PyPI's version with our own. 810 if result is not None: 811 ### We have a result from PyPI and a stated required version. 812 if required_version: 813 satisfied = _version_satisfies(result.available_version, required_version, debug=debug) 814 return (not satisfied) if satisfied is not None else False 815 816 ### If `check_pypi` and we don't have a required version, check if PyPI's version 817 ### is newer than the installed version. 818 else: 819 return ( 820 packaging_version.parse(result.available_version) > 821 packaging_version.parse(version) 822 ) 823 824 ### We might be depending on a prerelease. 825 ### Sanity check that the required version is not greater than the installed version. 826 required_version = ( 827 required_version.replace(_MRSM_PACKAGE_ARCHIVES_PREFIX, '') 828 .replace(' @ ', '').replace('wheels', '').replace('+mrsm', '').replace('/-', '') 829 .replace('-py3-none-any.whl', '') 830 ) 831 832 ### An unknown answer (neither side parses as PEP 440) must not trigger an install. 833 satisfied = _version_satisfies(raw_version, required_version, debug=debug) 834 return (not satisfied) if satisfied is not None else False
Check if a Meerschaum dependency needs an update. Returns a bool for whether or not a package needs to be updated.
Parameters
- package ('ModuleType'): The module of the package to be updated.
- install_name (Optional[str], default None):
If provided, use this string to determine the required version.
Otherwise use the install name defined in
meerschaum.utils.packages._packages. - import_name:: If provided, override the package's
__name__string. - version (Optional[str], default None):
If specified, override the package's
__version__string. - check_pypi (bool, default False):
If
True, check pypi.org for updates. Defaults toFalse. - split (bool, default True):
If
True, split the module's name on periods to detrive the root name. Defaults toTrue. - color (bool, default True):
If
True, format debug output. Defaults toTrue. - debug (bool, default True): Verbosity toggle.
Returns
- A bool indicating whether the package requires an update.
837def get_pip( 838 venv: Optional[str] = 'mrsm', 839 color: bool = True, 840 debug: bool = False, 841) -> bool: 842 """ 843 Download and run the get-pip.py script. 844 845 Parameters 846 ---------- 847 venv: Optional[str], default 'mrsm' 848 The virtual environment into which to install `pip`. 849 850 color: bool, default True 851 If `True`, force color output. 852 853 debug: bool, default False 854 Verbosity toggle. 855 856 Returns 857 ------- 858 A bool indicating success. 859 860 """ 861 import sys 862 import subprocess 863 import meerschaum.config.paths as paths 864 from meerschaum.utils.misc import wget 865 from meerschaum._internal.static import STATIC_CONFIG 866 url = STATIC_CONFIG['system']['urls']['get-pip.py'] 867 dest = paths.CACHE_RESOURCES_PATH / 'get-pip.py' 868 try: 869 wget(url, dest, color=False, debug=debug) 870 except Exception: 871 print(f"Failed to fetch pip from '{url}'. Please install pip and restart Meerschaum.") 872 sys.exit(1) 873 if venv is not None: 874 init_venv(venv=venv, debug=debug) 875 cmd_list = [venv_executable(venv=venv), dest.as_posix()] 876 return subprocess.call(cmd_list, env=_get_pip_os_env(color=color)) == 0
Download and run the get-pip.py script.
Parameters
- venv (Optional[str], default 'mrsm'):
The virtual environment into which to install
pip. - color (bool, default True):
If
True, force color output. - debug (bool, default False): Verbosity toggle.
Returns
- A bool indicating success.
879def get_pip_install_plan( 880 *install_names: str, 881 args: Optional[List[str]] = None, 882 requirements_file_path: Union[pathlib.Path, str, None] = None, 883 venv: Optional[str] = 'mrsm', 884 _uninstall: bool = False, 885 _install_uv_pip: bool = True, 886 _use_uv_pip: bool = True, 887 debug: bool = False, 888) -> Dict[str, Any]: 889 """Return a read-only summary of a package installation request.""" 890 try: 891 import pip # noqa: F401 892 have_pip = True 893 except ImportError: 894 have_pip = False 895 896 uv_bin = _get_uv_bin() 897 898 use_uv_pip = bool( 899 _use_uv_pip 900 and uv_bin 901 and is_uv_enabled() 902 ) 903 requested_packages = [ 904 ( 905 get_install_no_version(install_name) 906 if _uninstall or install_name.startswith(_MRSM_PACKAGE_ARCHIVES_PREFIX) 907 else install_name 908 ) 909 for install_name in install_names 910 ] 911 auto_install_enabled = _auto_install_allowed() 912 return { 913 'operation': 'uninstall' if _uninstall else 'install', 914 'environment': venv, 915 'target': str(_get_pip_install_target_path(venv)), 916 'packages': requested_packages, 917 'requirements_file': ( 918 str(pathlib.Path(requirements_file_path).resolve()) 919 if requirements_file_path is not None 920 else None 921 ), 922 'args': list(args if args is not None else ([] if _uninstall else ['--upgrade'])), 923 'installer': 'uv' if use_uv_pip else 'pip', 924 'installer_available': bool(use_uv_pip or have_pip), 925 'pip_fallback': bool(use_uv_pip and have_pip), 926 'auto_install_enabled': auto_install_enabled, 927 'would_bootstrap_uv': bool( 928 not use_uv_pip 929 and not uv_bin 930 and have_pip 931 and _install_uv_pip 932 and is_uv_enabled() 933 ), 934 'lock_path': str(get_pip_install_lock_path(venv)), 935 }
Return a read-only summary of a package installation request.
938@_locked_pip_install 939def pip_install( 940 *install_names: str, 941 args: Optional[List[str]] = None, 942 requirements_file_path: Union[pathlib.Path, str, None] = None, 943 venv: Optional[str] = 'mrsm', 944 split: bool = False, 945 check_update: bool = True, 946 check_pypi: bool = True, 947 check_wheel: bool = True, 948 _uninstall: bool = False, 949 _from_completely_uninstall: bool = False, 950 _install_uv_pip: bool = True, 951 _use_uv_pip: bool = True, 952 _implicit: bool = False, 953 color: bool = True, 954 silent: bool = False, 955 dry_run: bool = False, 956 debug: bool = False, 957) -> bool: 958 """ 959 Install packages from PyPI with `pip`. 960 961 When `MRSM_NO_AUTO_INSTALL` is set, calling this function directly still installs the 962 requested packages, but never bootstraps `uv`, `pip`, `wheel` or `setuptools` on its own 963 and never checks PyPI for a newer `pip`. Calls made on behalf of an import or a dependency 964 precheck (`_implicit=True`) install nothing and return `False`. 965 966 Parameters 967 ---------- 968 *install_names: str 969 The installation names of packages to be installed. 970 This includes version restrictions. 971 Use `_import_to_install_name()` to get the predefined `install_name` for a package 972 from its import name. 973 974 args: Optional[List[str]], default None 975 A list of command line arguments to pass to `pip`. 976 If not provided, default to `['--upgrade']` if `_uninstall` is `False`, else `[]`. 977 978 requirements_file_path: Optional[pathlib.Path, str], default None 979 If provided, append `['-r', '/path/to/requirements.txt']` to `args`. 980 981 venv: str, default 'mrsm' 982 The virtual environment to install into. 983 984 split: bool, default False 985 If `True`, split on periods and only install the root package name. 986 987 check_update: bool, default True 988 If `True`, check if the package requires an update. 989 990 check_pypi: bool, default True 991 If `True` and `check_update` is `True`, check PyPI for the latest version. 992 993 check_wheel: bool, default True 994 If `True`, check if `wheel` is available. 995 996 _uninstall: bool, default False 997 If `True`, uninstall packages instead. 998 999 color: bool, default True 1000 If `True`, include color in debug text. 1001 1002 silent: bool, default False 1003 If `True`, skip printing messages. 1004 1005 dry_run: bool, default False 1006 If `True`, print the read-only installation plan without changing the environment. 1007 1008 debug: bool, default False 1009 Verbosity toggle. 1010 1011 Returns 1012 ------- 1013 A bool indicating success. 1014 1015 """ 1016 import meerschaum.config.paths as paths 1017 from meerschaum._internal.static import STATIC_CONFIG 1018 from meerschaum.utils.warnings import warn 1019 auto_install_allowed = _auto_install_allowed() 1020 if dry_run: 1021 import json 1022 plan = get_pip_install_plan( 1023 *install_names, 1024 args=args, 1025 requirements_file_path=requirements_file_path, 1026 venv=venv, 1027 _uninstall=_uninstall, 1028 _install_uv_pip=_install_uv_pip, 1029 _use_uv_pip=_use_uv_pip, 1030 debug=debug, 1031 ) 1032 if not silent: 1033 print(json.dumps(plan, indent=2)) 1034 return True 1035 1036 if args is None: 1037 args = ['--upgrade'] if not _uninstall else [] 1038 ANSI = True if color else False 1039 daemon_env_var = STATIC_CONFIG['environment']['daemon_id'] 1040 inside_daemon = daemon_env_var in os.environ 1041 if inside_daemon: 1042 silent = True 1043 1044 _args = list(args) 1045 pip_venv = None 1046 try: 1047 import pip 1048 have_pip = True 1049 except ImportError: 1050 have_pip = False 1051 uv_bin = _get_uv_bin() 1052 have_uv_pip = uv_bin is not None 1053 1054 if ( 1055 auto_install_allowed 1056 and have_pip 1057 and not have_uv_pip 1058 and _install_uv_pip 1059 and is_uv_enabled() 1060 ): 1061 if not pip_install( 1062 'uv', 1063 venv=None, 1064 debug=debug, 1065 _install_uv_pip=False, 1066 check_update=False, 1067 check_pypi=False, 1068 check_wheel=False, 1069 ) and not silent: 1070 warn( 1071 f"Failed to install `uv` for virtual environment '{venv}'.", 1072 color=False, 1073 ) 1074 # The bootstrap may have made uv available in this interpreter or on PATH. 1075 uv_bin = _get_uv_bin() 1076 1077 use_uv_pip = ( 1078 _use_uv_pip 1079 and uv_bin is not None 1080 and is_uv_enabled() 1081 ) 1082 # uv does not need wheel, setuptools, or pip in either interpreter. Checking their 1083 # versions first recursively bootstraps the very installer we are trying to select. 1084 have_wheel = ( 1085 venv_contains_package('wheel', venv=venv, debug=debug) 1086 if check_wheel and not use_uv_pip else False 1087 ) 1088 1089 import sys 1090 if not have_pip and not use_uv_pip: 1091 have_mrsm_pip = venv_contains_package('pip', venv='mrsm') 1092 if not have_mrsm_pip and not auto_install_allowed: 1093 if not silent: 1094 warn( 1095 "Neither `uv` nor `pip` is available to install packages, " 1096 + f"and {NO_AUTO_INSTALL_ENV_VAR} forbids downloading them.", 1097 stack=False, 1098 color=False, 1099 ) 1100 return False 1101 if not have_mrsm_pip and not get_pip(venv=venv, color=color, debug=debug): 1102 import sys 1103 minor = sys.version_info.minor 1104 print( 1105 "\nFailed to import `pip` and `ensurepip`.\n" 1106 + "If you are running Ubuntu/Debian, " 1107 + f"you might need to install `python3.{minor}-distutils`:\n\n" 1108 + f" sudo apt install python3.{minor}-pip python3.{minor}-venv\n\n" 1109 + "Please install pip and restart Meerschaum.\n\n" 1110 + "You can find instructions on installing `pip` here:\n" 1111 + "https://pip.pypa.io/en/stable/installing/" 1112 ) 1113 sys.exit(1) 1114 1115 pip = attempt_import('pip', lazy=False) 1116 pip_venv = 'mrsm' 1117 1118 with Venv(venv, debug=debug): 1119 if venv is not None: 1120 if ( 1121 '--ignore-installed' not in args 1122 and '-I' not in _args 1123 and not _uninstall 1124 and not use_uv_pip 1125 ): 1126 _args += ['--ignore-installed'] 1127 if '--cache-dir' not in args and not _uninstall: 1128 cache_dir_path = paths.VIRTENV_RESOURCES_PATH / venv / 'cache' 1129 _args += ['--cache-dir', str(cache_dir_path)] 1130 1131 if 'pip' not in ' '.join(_args) and not use_uv_pip: 1132 if check_update and not _uninstall and auto_install_allowed: 1133 pip = attempt_import('pip', venv=venv, install=False, debug=debug, lazy=False) 1134 if need_update(pip, check_pypi=check_pypi, debug=debug): 1135 _args.append(all_packages['pip']) 1136 1137 _args = (['install'] if not _uninstall else ['uninstall']) + _args 1138 1139 if check_wheel and not _uninstall and not use_uv_pip and auto_install_allowed: 1140 if not have_wheel: 1141 setup_packages_to_install = ( 1142 ['setuptools', 'wheel', 'PyYAML'] 1143 + (['uv'] if is_uv_enabled() else []) 1144 ) 1145 if not pip_install( 1146 *setup_packages_to_install, 1147 venv=venv, 1148 check_update=False, 1149 check_pypi=False, 1150 check_wheel=False, 1151 debug=debug, 1152 _install_uv_pip=False, 1153 ) and not silent: 1154 from meerschaum.utils.misc import items_str 1155 warn( 1156 ( 1157 f"Failed to install {items_str(setup_packages_to_install)} for virtual " 1158 + f"environment '{venv}'." 1159 ), 1160 color=False, 1161 ) 1162 1163 if requirements_file_path is not None: 1164 _args.append('-r') 1165 _args.append(pathlib.Path(requirements_file_path).resolve().as_posix()) 1166 1167 if not ANSI and '--no-color' not in _args: 1168 _args.append('--no-color') 1169 1170 if '--no-input' not in _args and not use_uv_pip: 1171 _args.append('--no-input') 1172 1173 if _uninstall and '-y' not in _args and not use_uv_pip: 1174 _args.append('-y') 1175 1176 ### `uv pip uninstall` has no `-y` (it never prompts) and rejects it. 1177 if _uninstall and use_uv_pip: 1178 _args = [arg for arg in _args if arg not in ('-y', '--yes')] 1179 1180 if '--no-warn-conflicts' not in _args and not _uninstall and not use_uv_pip: 1181 _args.append('--no-warn-conflicts') 1182 1183 if '--disable-pip-version-check' not in _args and not use_uv_pip: 1184 _args.append('--disable-pip-version-check') 1185 1186 if '--target' not in _args and '-t' not in _args and not (not use_uv_pip and _uninstall): 1187 if venv is not None: 1188 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 1189 if not vtp.exists(): 1190 if not init_venv(venv, force=True): 1191 vtp.mkdir(parents=True, exist_ok=True) 1192 _args += ['--target', venv_target_path(venv, debug=debug).as_posix()] 1193 elif ( 1194 '--target' not in _args 1195 and '-t' not in _args 1196 and not inside_venv() 1197 and not _uninstall 1198 and not use_uv_pip 1199 ): 1200 _args.append('--user') 1201 1202 if venv is None and '--break-system-packages' not in _args: 1203 _args.append('--break-system-packages') 1204 1205 if debug: 1206 if '-v' not in _args or '-vv' not in _args or '-vvv' not in _args: 1207 if use_uv_pip: 1208 _args.append('--verbose') 1209 else: 1210 if '-q' not in _args or '-qq' not in _args or '-qqq' not in _args: 1211 pass 1212 1213 _packages = [ 1214 ( 1215 get_install_no_version(install_name) 1216 if _uninstall or install_name.startswith(_MRSM_PACKAGE_ARCHIVES_PREFIX) 1217 else install_name 1218 ) 1219 for install_name in install_names 1220 ] 1221 msg = "Installing packages:" if not _uninstall else "Uninstalling packages:" 1222 for p in _packages: 1223 msg += f'\n - {p}' 1224 if not silent: 1225 print(msg) 1226 1227 if _uninstall and not _from_completely_uninstall and not use_uv_pip: 1228 for install_name in _packages: 1229 _install_no_version = get_install_no_version(install_name) 1230 if _install_no_version in ('pip', 'wheel', 'uv'): 1231 continue 1232 if not completely_uninstall_package( 1233 _install_no_version, 1234 venv=venv, 1235 debug=debug, 1236 ) and not silent: 1237 warn( 1238 f"Failed to clean up package '{_install_no_version}'.", 1239 ) 1240 1241 ### NOTE: Only append the `--prerelease=allow` flag if we explicitly depend on a prerelease. 1242 if use_uv_pip: 1243 _args.insert(0, 'pip') 1244 if not _uninstall and get_prerelease_dependencies(_packages): 1245 _args.append('--prerelease=allow') 1246 1247 rc = run_python_package( 1248 ('pip' if not use_uv_pip else 'uv'), 1249 _args + _packages, 1250 venv=pip_venv, 1251 env=_get_pip_os_env(color=color), 1252 debug=debug, 1253 ) 1254 if debug: 1255 print(f"{rc=}") 1256 success = rc == 0 1257 1258 if success: 1259 with _locks['_is_installed_first_check']: 1260 _is_installed_first_check.clear() 1261 _update_request_ledger(_packages, venv, _uninstall) 1262 1263 msg = ( 1264 "Successfully " + ('un' if _uninstall else '') + "installed packages." if success 1265 else "Failed to " + ('un' if _uninstall else '') + "install packages." 1266 ) 1267 if not silent: 1268 print(msg) 1269 if debug and not silent: 1270 print('pip ' + ('un' if _uninstall else '') + 'install returned:', success) 1271 return success
Install packages from PyPI with pip.
When MRSM_NO_AUTO_INSTALL is set, calling this function directly still installs the
requested packages, but never bootstraps uv, pip, wheel or setuptools on its own
and never checks PyPI for a newer pip. Calls made on behalf of an import or a dependency
precheck (_implicit=True) install nothing and return False.
Parameters
- *install_names (str):
The installation names of packages to be installed.
This includes version restrictions.
Use
_import_to_install_name()to get the predefinedinstall_namefor a package from its import name. - args (Optional[List[str]], default None):
A list of command line arguments to pass to
pip. If not provided, default to['--upgrade']if_uninstallisFalse, else[]. - requirements_file_path (Optional[pathlib.Path, str], default None):
If provided, append
['-r', '/path/to/requirements.txt']toargs. - venv (str, default 'mrsm'): The virtual environment to install into.
- split (bool, default False):
If
True, split on periods and only install the root package name. - check_update (bool, default True):
If
True, check if the package requires an update. - check_pypi (bool, default True):
If
Trueandcheck_updateisTrue, check PyPI for the latest version. - check_wheel (bool, default True):
If
True, check ifwheelis available. - _uninstall (bool, default False):
If
True, uninstall packages instead. - color (bool, default True):
If
True, include color in debug text. - silent (bool, default False):
If
True, skip printing messages. - dry_run (bool, default False):
If
True, print the read-only installation plan without changing the environment. - debug (bool, default False): Verbosity toggle.
Returns
- A bool indicating success.
1274def get_prerelease_dependencies(_packages: Optional[List[str]] = None): 1275 """ 1276 Return a list of explicitly prerelease dependencies from a list of packages. 1277 """ 1278 if _packages is None: 1279 _packages = list(all_packages.keys()) 1280 prelrease_strings = ['dev', 'rc', 'a'] 1281 prerelease_packages = [] 1282 for install_name in _packages: 1283 _install_no_version = get_install_no_version(install_name) 1284 import_name = _install_to_import_name(install_name) 1285 install_with_version = _import_to_install_name(import_name) 1286 version_only = ( 1287 install_with_version.lower().replace(_install_no_version.lower(), '') 1288 .split(']')[-1] 1289 ) 1290 1291 is_prerelease = False 1292 for prelrease_string in prelrease_strings: 1293 if prelrease_string in version_only: 1294 is_prerelease = True 1295 1296 if is_prerelease: 1297 prerelease_packages.append(install_name) 1298 return prerelease_packages
Return a list of explicitly prerelease dependencies from a list of packages.
1301def completely_uninstall_package( 1302 install_name: str, 1303 venv: str = 'mrsm', 1304 debug: bool = False, 1305) -> bool: 1306 """ 1307 Continue calling `pip uninstall` until a package is completely 1308 removed from a virtual environment. 1309 This is useful for dealing with multiple installed versions of a package. 1310 """ 1311 attempts = 0 1312 _install_no_version = get_install_no_version(install_name) 1313 clean_install_no_version = _install_no_version.lower().replace('-', '_') 1314 installed_versions = [] 1315 vtp = venv_target_path(venv, allow_nonexistent=True, debug=debug) 1316 if not vtp.exists(): 1317 return True 1318 1319 for file_name in os.listdir(vtp): 1320 if not file_name.endswith('.dist-info'): 1321 continue 1322 clean_dist_info = file_name.replace('-', '_').lower() 1323 if not clean_dist_info.startswith(clean_install_no_version): 1324 continue 1325 installed_versions.append(file_name) 1326 1327 max_attempts = len(installed_versions) 1328 while attempts < max_attempts: 1329 if not venv_contains_package( 1330 _install_to_import_name(_install_no_version), 1331 venv=venv, debug=debug, 1332 ): 1333 return True 1334 if not pip_uninstall( 1335 _install_no_version, 1336 venv = venv, 1337 silent = (not debug), 1338 _from_completely_uninstall = True, 1339 debug = debug, 1340 ): 1341 return False 1342 attempts += 1 1343 return False
Continue calling pip uninstall until a package is completely
removed from a virtual environment.
This is useful for dealing with multiple installed versions of a package.
1346def pip_uninstall( 1347 *args, **kw 1348) -> bool: 1349 """ 1350 Uninstall Python packages. 1351 This function is a wrapper around `pip_install()` but with `_uninstall` enforced as `True`. 1352 """ 1353 return pip_install(*args, _uninstall=True, **{k: v for k, v in kw.items() if k != '_uninstall'})
Uninstall Python packages.
This function is a wrapper around pip_install() but with _uninstall enforced as True.
1356def run_python_package( 1357 package_name: str, 1358 args: Optional[List[str]] = None, 1359 venv: Optional[str] = 'mrsm', 1360 cwd: Optional[str] = None, 1361 env: Optional[Dict[str, str]] = None, 1362 foreground: bool = False, 1363 as_proc: bool = False, 1364 capture_output: bool = False, 1365 debug: bool = False, 1366 **kw: Any, 1367) -> Union[int, subprocess.Popen, None]: 1368 """ 1369 Runs an installed python package. 1370 E.g. Translates to `/usr/bin/python -m [package]` 1371 1372 Parameters 1373 ---------- 1374 package_name: str 1375 The Python module to be executed. 1376 1377 args: Optional[List[str]], default None 1378 Additional command line arguments to be appended after `-m [package]`. 1379 1380 venv: Optional[str], default 'mrsm' 1381 If specified, execute the Python interpreter from a virtual environment. 1382 1383 cwd: Optional[str], default None 1384 If specified, change directories before starting the process. 1385 Defaults to `None`. 1386 1387 env: Optional[Dict[str, str]], default None 1388 If specified, only use the provided dictionary for the environment variables. 1389 Defaults to `os.environ`. 1390 1391 as_proc: bool, default False 1392 If `True`, return a `subprocess.Popen` object. 1393 1394 capture_output: bool, default False 1395 If `as_proc` is `True`, capture stdout and stderr. 1396 1397 foreground: bool, default False 1398 If `True`, start the subprocess as a foreground process. 1399 Defaults to `False`. 1400 1401 kw: Any 1402 Additional keyword arguments to pass to `meerschaum.utils.process.run_process()` 1403 and by extension `subprocess.Popen()`. 1404 1405 Returns 1406 ------- 1407 Either a return code integer or a `subprocess.Popen` object 1408 (or `None` if a `KeyboardInterrupt` occurs and as_proc is `True`). 1409 """ 1410 import sys 1411 import subprocess 1412 import traceback 1413 import meerschaum.config.paths as paths 1414 from meerschaum.utils.process import run_process 1415 from meerschaum.utils.warnings import warn 1416 if args is None: 1417 args = [] 1418 old_cwd = os.getcwd() 1419 if cwd is not None: 1420 os.chdir(cwd) 1421 executable = venv_executable(venv=venv) 1422 venv_path = (paths.VIRTENV_RESOURCES_PATH / venv) if venv is not None else None 1423 from meerschaum.config.environment import get_child_env 1424 env_dict = get_child_env(env if isinstance(env, dict) else (os.environ or {})) 1425 if venv_path is not None: 1426 env_dict.update({'VIRTUAL_ENV': venv_path.as_posix()}) 1427 uv_bin = _get_uv_bin() if package_name == 'uv' else None 1428 command = ( 1429 [uv_bin] if uv_bin is not None else [executable, '-m', str(package_name)] 1430 ) + [str(a) for a in args] 1431 if debug: 1432 print(command, file=sys.stderr) 1433 try: 1434 to_return = run_process( 1435 command, 1436 foreground=foreground, 1437 as_proc=as_proc, 1438 capture_output=capture_output, 1439 env=env_dict, 1440 **kw 1441 ) 1442 except Exception: 1443 msg = f"Failed to execute {command}, will try again:\n{traceback.format_exc()}" 1444 warn(msg, color=False) 1445 stdout, stderr = ( 1446 (None, None) 1447 if not capture_output 1448 else (subprocess.PIPE, subprocess.PIPE) 1449 ) 1450 proc = subprocess.Popen( 1451 command, 1452 stdout=stdout, 1453 stderr=stderr, 1454 stdin=sys.stdin, 1455 env=env_dict, 1456 ) 1457 to_return = proc if as_proc else proc.wait() 1458 except KeyboardInterrupt: 1459 to_return = 1 if not as_proc else None 1460 os.chdir(old_cwd) 1461 return to_return
Runs an installed python package.
E.g. Translates to /usr/bin/python -m [package]
Parameters
- package_name (str): The Python module to be executed.
- args (Optional[List[str]], default None):
Additional command line arguments to be appended after
-m [package]. - venv (Optional[str], default 'mrsm'): If specified, execute the Python interpreter from a virtual environment.
- cwd (Optional[str], default None):
If specified, change directories before starting the process.
Defaults to
None. - env (Optional[Dict[str, str]], default None):
If specified, only use the provided dictionary for the environment variables.
Defaults to
os.environ. - as_proc (bool, default False):
If
True, return asubprocess.Popenobject. - capture_output (bool, default False):
If
as_procisTrue, capture stdout and stderr. - foreground (bool, default False):
If
True, start the subprocess as a foreground process. Defaults toFalse. - kw (Any):
Additional keyword arguments to pass to
meerschaum.utils.process.run_process()and by extensionsubprocess.Popen().
Returns
- Either a return code integer or a
subprocess.Popenobject - (or
Noneif aKeyboardInterruptoccurs and as_proc isTrue).
1505def attempt_import( 1506 *names: str, 1507 lazy: bool = True, 1508 warn: bool = True, 1509 install: bool = True, 1510 venv: Optional[str] = 'mrsm', 1511 precheck: bool = True, 1512 split: bool = True, 1513 check_update: bool = False, 1514 check_pypi: bool = False, 1515 check_is_installed: bool = True, 1516 allow_outside_venv: bool = True, 1517 color: bool = True, 1518 debug: bool = False 1519) -> Any: 1520 """ 1521 Raise a warning if packages are not installed; otherwise import and return modules. 1522 If `lazy` is `True`, return lazy-imported modules. 1523 1524 Returns tuple of modules if multiple names are provided, else returns one module. 1525 1526 Parameters 1527 ---------- 1528 names: List[str] 1529 The packages to be imported. 1530 1531 lazy: bool, default True 1532 If `True`, lazily load packages. 1533 1534 warn: bool, default True 1535 If `True`, raise a warning if a package cannot be imported. 1536 1537 install: bool, default True 1538 If `True`, attempt to install a missing package into the designated virtual environment. 1539 If `check_update` is True, install updates if available. 1540 1541 venv: Optional[str], default 'mrsm' 1542 The virtual environment in which to search for packages and to install packages into. 1543 1544 precheck: bool, default True 1545 If `True`, attempt to find module before importing (necessary for checking if modules exist 1546 and retaining lazy imports), otherwise assume lazy is `False`. 1547 1548 split: bool, default True 1549 If `True`, split packages' names on `'.'`. 1550 1551 check_update: bool, default False 1552 If `True` and `install` is `True`, install updates if the required minimum version 1553 does not match. 1554 1555 check_pypi: bool, default False 1556 If `True` and `check_update` is `True`, check PyPI when determining whether 1557 an update is required. 1558 1559 check_is_installed: bool, default True 1560 If `True`, check if the package is contained in the virtual environment. 1561 1562 allow_outside_venv: bool, default True 1563 If `True`, search outside of the specified virtual environment 1564 if the package cannot be found. 1565 Setting to `False` will reinstall the package into a virtual environment, even if it 1566 is installed outside. 1567 1568 color: bool, default True 1569 If `False`, do not print ANSI colors. 1570 1571 Returns 1572 ------- 1573 The specified modules. If they're not available and `install` is `True`, it will first 1574 download them into a virtual environment and return the modules. 1575 1576 Examples 1577 -------- 1578 >>> pandas, sqlalchemy = attempt_import('pandas', 'sqlalchemy') 1579 >>> pandas = attempt_import('pandas') 1580 1581 """ 1582 1583 import importlib.util 1584 1585 if os.environ.get('MRSM_API_EXECUTION') == '1': 1586 return _prepared_execution_import(names, lazy=lazy, precheck=precheck, warn=warn) 1587 1588 global emitted_auto_install_warning 1589 no_auto_install_env_var = NO_AUTO_INSTALL_ENV_VAR 1590 if not _auto_install_allowed(): 1591 install = False 1592 1593 ### Cosmetic packages are never installed on import: without them output is plain text. 1594 if any(name.split('.')[0] in _NEVER_AUTO_INSTALLED for name in names): 1595 install = False 1596 warn = False 1597 1598 ### to prevent recursion, check if parent Meerschaum package is being imported 1599 if names == ('meerschaum',): 1600 return _import_module('meerschaum') 1601 1602 if venv == 'mrsm' and _import_hook_venv is not None: 1603 if debug: 1604 print(f"Import hook for virtual environment '{_import_hook_venv}' is active.") 1605 venv = _import_hook_venv 1606 1607 _warnings = _import_module('meerschaum.utils.warnings') 1608 warn_function = _warnings.warn 1609 1610 def do_import(_name: str, **kw) -> Union['ModuleType', None]: 1611 ### A fully-imported module resolves from `sys.modules` regardless of the active venv, 1612 ### so skip activating the venv (which resolves and creates its directories). 1613 import sys 1614 loaded_module = sys.modules.get(_name, None) 1615 if ( 1616 loaded_module is not None 1617 and not getattr(getattr(loaded_module, '__spec__', None), '_initializing', False) 1618 ): 1619 return loaded_module 1620 1621 with Venv(venv=venv, debug=debug): 1622 ### determine the import method (lazy vs normal) 1623 from meerschaum.utils.misc import filter_keywords 1624 import_method = ( 1625 _import_module if not lazy 1626 else lazy_import 1627 ) 1628 try: 1629 mod = import_method(_name, **(filter_keywords(import_method, **kw))) 1630 except Exception as e: 1631 if warn: 1632 import traceback 1633 traceback.print_exception(type(e), e, e.__traceback__) 1634 warn_function( 1635 f"Failed to import module '{_name}'.\nException:\n{e}", 1636 ImportWarning, 1637 stacklevel = (5 if lazy else 4), 1638 color = False, 1639 ) 1640 mod = None 1641 return mod 1642 1643 modules = [] 1644 for name in names: 1645 ### Check if package is a declared dependency. 1646 root_name = name.split('.')[0] if split else name 1647 install_name = _import_to_install_name(root_name) 1648 1649 if install_name is None: 1650 install_name = root_name 1651 if warn and root_name != 'plugins': 1652 warn_function( 1653 f"Package '{root_name}' is not declared in meerschaum.utils.packages.", 1654 ImportWarning, 1655 stacklevel = 3, 1656 color = False 1657 ) 1658 1659 ### Determine if the package exists. 1660 if precheck is False: 1661 found_module = ( 1662 do_import( 1663 name, debug=debug, warn=False, venv=venv, color=color, 1664 check_update=False, check_pypi=False, split=split, 1665 ) is not None 1666 ) 1667 else: 1668 installed_cache_key = (name, venv, split, allow_outside_venv) 1669 if check_is_installed: 1670 with _locks['_is_installed_first_check']: 1671 if not _is_installed_first_check.get(installed_cache_key, False): 1672 package_is_installed = is_installed( 1673 name, 1674 venv = venv, 1675 split = split, 1676 allow_outside_venv = allow_outside_venv, 1677 debug = debug, 1678 ) 1679 if package_is_installed: 1680 _is_installed_first_check[installed_cache_key] = True 1681 else: 1682 package_is_installed = True 1683 else: 1684 package_is_installed = venv_contains_package( 1685 name, 1686 venv=venv, 1687 split=split, 1688 debug=debug, 1689 ) 1690 found_module = package_is_installed 1691 1692 if not found_module: 1693 if install: 1694 with _locks['emitted_auto_install_warning']: 1695 if warn and not emitted_auto_install_warning: 1696 emitted_auto_install_warning = True 1697 warn_function( 1698 "Meerschaum is installing a missing runtime dependency. " 1699 + f"Set {no_auto_install_env_var}=1 to disable automatic downloads.", 1700 ImportWarning, 1701 stacklevel=3, 1702 color=False, 1703 ) 1704 if not pip_install( 1705 install_name, 1706 venv = venv, 1707 split = False, 1708 check_update = check_update, 1709 color = color, 1710 debug = debug, 1711 _implicit = True, 1712 ): 1713 if warn: 1714 warn_function( 1715 f"Failed to install '{install_name}'.", 1716 ImportWarning, 1717 stacklevel = 3, 1718 color = False, 1719 ) 1720 else: 1721 _record_import_request(install_name, venv) 1722 elif warn: 1723 ### Raise a warning if we can't find the package and install = False. 1724 warn_function( 1725 (f"\n\nMissing package '{name}' from virtual environment '{venv}'; " 1726 + "some features will not work correctly." 1727 + ( 1728 f"\n\nUnset {no_auto_install_env_var} to allow package installation.\n" 1729 if no_auto_install_env_var in os.environ 1730 else "\n\nSet install=True when calling attempt_import.\n" 1731 )), 1732 ImportWarning, 1733 stacklevel = 3, 1734 color = False, 1735 ) 1736 1737 elif found_module: 1738 _record_import_request(install_name, venv, only_plugins=True) 1739 1740 ### Do the import. Will be lazy if lazy=True. 1741 m = do_import( 1742 name, debug=debug, warn=warn, venv=venv, color=color, 1743 check_update=check_update, check_pypi=check_pypi, install=install, split=split, 1744 ) 1745 modules.append(m) 1746 1747 modules = tuple(modules) 1748 if len(modules) == 1: 1749 return modules[0] 1750 return modules
Raise a warning if packages are not installed; otherwise import and return modules.
If lazy is True, return lazy-imported modules.
Returns tuple of modules if multiple names are provided, else returns one module.
Parameters
- names (List[str]): The packages to be imported.
- lazy (bool, default True):
If
True, lazily load packages. - warn (bool, default True):
If
True, raise a warning if a package cannot be imported. - install (bool, default True):
If
True, attempt to install a missing package into the designated virtual environment. Ifcheck_updateis True, install updates if available. - venv (Optional[str], default 'mrsm'): The virtual environment in which to search for packages and to install packages into.
- precheck (bool, default True):
If
True, attempt to find module before importing (necessary for checking if modules exist and retaining lazy imports), otherwise assume lazy isFalse. - split (bool, default True):
If
True, split packages' names on'.'. - check_update (bool, default False):
If
TrueandinstallisTrue, install updates if the required minimum version does not match. - check_pypi (bool, default False):
If
Trueandcheck_updateisTrue, check PyPI when determining whether an update is required. - check_is_installed (bool, default True):
If
True, check if the package is contained in the virtual environment. - allow_outside_venv (bool, default True):
If
True, search outside of the specified virtual environment if the package cannot be found. Setting toFalsewill reinstall the package into a virtual environment, even if it is installed outside. - color (bool, default True):
If
False, do not print ANSI colors.
Returns
- The specified modules. If they're not available and
installisTrue, it will first - download them into a virtual environment and return the modules.
Examples
>>> pandas, sqlalchemy = attempt_import('pandas', 'sqlalchemy')
>>> pandas = attempt_import('pandas')
1794def lazy_import( 1795 name: str, 1796 local_name: str = None, 1797 **kw 1798) -> meerschaum.utils.packages.lazy_loader.LazyLoader: 1799 """ 1800 Lazily import a package. 1801 """ 1802 from meerschaum.utils.packages.lazy_loader import LazyLoader 1803 if local_name is None: 1804 local_name = name 1805 return LazyLoader( 1806 local_name, 1807 globals(), 1808 name, 1809 **kw 1810 )
Lazily import a package.
1813def pandas_name() -> str: 1814 """ 1815 Return the configured name for `pandas`. 1816 1817 Below are the expected possible values: 1818 1819 - 'pandas' 1820 - 'modin.pandas' 1821 - 'dask.dataframe' 1822 1823 """ 1824 from meerschaum.config import get_config 1825 pandas_module_name = get_config('system', 'connectors', 'all', 'pandas', patch=True) 1826 if pandas_module_name == 'modin': 1827 pandas_module_name = 'modin.pandas' 1828 elif pandas_module_name == 'dask': 1829 pandas_module_name = 'dask.dataframe' 1830 1831 return pandas_module_name
Return the configured name for pandas.
Below are the expected possible values:
- 'pandas'
- 'modin.pandas'
- 'dask.dataframe'
1835def import_pandas( 1836 debug: bool = False, 1837 lazy: bool = False, 1838 **kw 1839) -> 'ModuleType': 1840 """ 1841 Quality-of-life function to attempt to import the configured version of `pandas`. 1842 """ 1843 pandas_module_name = pandas_name() 1844 global emitted_pandas_warning 1845 1846 if pandas_module_name != 'pandas': 1847 with _locks['emitted_pandas_warning']: 1848 if not emitted_pandas_warning: 1849 from meerschaum.utils.warnings import warn 1850 emitted_pandas_warning = True 1851 warn( 1852 ( 1853 "You are using an alternative Pandas implementation " 1854 + f"'{pandas_module_name}'" 1855 + "\n Features may not work as expected." 1856 ), 1857 stack=False, 1858 ) 1859 1860 pandas, pyarrow = attempt_import('pandas', 'pyarrow', debug=debug, lazy=False, **kw) 1861 pd = attempt_import(pandas_module_name, debug=debug, lazy=lazy, **kw) 1862 _warn_if_pandas_is_too_old(pandas) 1863 return pd
Quality-of-life function to attempt to import the configured version of pandas.
1889def import_rich( 1890 lazy: bool = True, 1891 debug: bool = False, 1892 **kw: Any 1893) -> 'ModuleType': 1894 """ 1895 Quality of life function for importing `rich`. 1896 """ 1897 from meerschaum.utils.formatting import ANSI, UNICODE 1898 ## need typing_extensions for `from rich import box` 1899 typing_extensions = attempt_import( 1900 'typing_extensions', lazy=False, debug=debug 1901 ) 1902 pygments = attempt_import( 1903 'pygments', lazy=False, 1904 ) 1905 rich = attempt_import( 1906 'rich', lazy=lazy, 1907 **kw 1908 ) 1909 return rich
Quality of life function for importing rich.
1923def import_dcc(warn=False, **kw) -> 'ModuleType': 1924 """ 1925 Import Dash Core Components (`dcc`). 1926 """ 1927 return ( 1928 attempt_import('dash_core_components', warn=warn, **kw) 1929 if _dash_less_than_2(warn=warn, **kw) else attempt_import('dash.dcc', warn=warn, **kw) 1930 )
Import Dash Core Components (dcc).
1933def import_html(warn=False, **kw) -> 'ModuleType': 1934 """ 1935 Import Dash HTML Components (`html`). 1936 """ 1937 return ( 1938 attempt_import('dash_html_components', warn=warn, **kw) 1939 if _dash_less_than_2(warn=warn, **kw) 1940 else attempt_import('dash.html', warn=warn, **kw) 1941 )
Import Dash HTML Components (html).
1944def get_modules_from_package( 1945 package: Any, 1946 names: bool = False, 1947 recursive: bool = False, 1948 lazy: bool = False, 1949 modules_venvs: bool = False, 1950 debug: bool = False 1951): 1952 """ 1953 Find and import all modules in a package. 1954 1955 Returns 1956 ------- 1957 Either list of modules or tuple of lists. 1958 """ 1959 from os.path import dirname, join, isfile, isdir, basename 1960 import glob 1961 1962 pattern = '*' if recursive else '*.py' 1963 package_path = dirname(package.__file__ or package.__path__[0]) 1964 module_names = glob.glob(join(package_path, pattern), recursive=recursive) 1965 _all = [ 1966 basename(f)[:-3] if isfile(f) else basename(f) 1967 for f in module_names 1968 if ((isfile(f) and f.endswith('.py')) or isdir(f)) 1969 and not f.endswith('__init__.py') 1970 and not f.endswith('__pycache__') 1971 ] 1972 ### 5.1: in an isolated team's sandboxed process the plugins package holds every team's 1973 ### links, but only the team's own plugins can be read. 1974 if package.__name__ == 'plugins': 1975 from meerschaum.plugins import sandboxed_plugins_names 1976 own = sandboxed_plugins_names() 1977 if own is not None: 1978 _all = [name for name in _all if name in own] 1979 1980 if debug: 1981 from meerschaum.utils.debug import dprint 1982 dprint(str(_all)) 1983 modules = [] 1984 for module_name in [package.__name__ + "." + mod_name for mod_name in _all]: 1985 ### there's probably a better way than a try: catch but it'll do for now 1986 try: 1987 ### if specified, activate the module's virtual environment before importing. 1988 ### NOTE: this only considers the filename, so two modules from different packages 1989 ### may end up sharing virtual environments. 1990 if modules_venvs: 1991 activate_venv(module_name.split('.')[-1], debug=debug) 1992 m = lazy_import(module_name, debug=debug) if lazy else _import_module(module_name) 1993 modules.append(m) 1994 except Exception: 1995 import traceback 1996 traceback.print_exc() 1997 finally: 1998 if modules_venvs: 1999 deactivate_venv(module_name.split('.')[-1], debug=debug) 2000 if names: 2001 return _all, modules 2002 2003 return modules
Find and import all modules in a package.
Returns
- Either list of modules or tuple of lists.
2006def import_children( 2007 package: Optional['ModuleType'] = None, 2008 package_name: Optional[str] = None, 2009 types : Optional[List[str]] = None, 2010 lazy: bool = True, 2011 recursive: bool = False, 2012 debug: bool = False 2013) -> List['ModuleType']: 2014 """ 2015 Import all functions in a package to its `__init__`. 2016 2017 Parameters 2018 ---------- 2019 package: Optional[ModuleType], default None 2020 Package to import its functions into. 2021 If `None` (default), use parent. 2022 2023 package_name: Optional[str], default None 2024 Name of package to import its functions into 2025 If None (default), use parent. 2026 2027 types: Optional[List[str]], default None 2028 Types of members to return. 2029 Defaults are `['method', 'builtin', 'class', 'function', 'package', 'module']` 2030 2031 Returns 2032 ------- 2033 A list of modules. 2034 """ 2035 import sys, inspect 2036 2037 if types is None: 2038 types = ['method', 'builtin', 'function', 'class', 'module'] 2039 2040 ### if package_name and package are None, use parent 2041 if package is None and package_name is None: 2042 package_name = inspect.stack()[1][0].f_globals['__name__'] 2043 2044 ### populate package or package_name from other other 2045 if package is None: 2046 package = sys.modules[package_name] 2047 elif package_name is None: 2048 package_name = package.__name__ 2049 2050 ### Set attributes in sys module version of package. 2051 ### Kinda like setting a dictionary 2052 ### functions[name] = func 2053 modules = get_modules_from_package(package, recursive=recursive, lazy=lazy, debug=debug) 2054 _all, members = [], [] 2055 objects = [] 2056 for module in modules: 2057 _objects = [] 2058 for ob in inspect.getmembers(module): 2059 for t in types: 2060 ### ob is a tuple of (name, object) 2061 if getattr(inspect, 'is' + t)(ob[1]): 2062 _objects.append(ob) 2063 2064 if 'module' in types: 2065 _objects.append((module.__name__.split('.')[0], module)) 2066 objects += _objects 2067 for ob in objects: 2068 setattr(sys.modules[package_name], ob[0], ob[1]) 2069 _all.append(ob[0]) 2070 members.append(ob[1]) 2071 2072 if debug: 2073 from meerschaum.utils.debug import dprint 2074 dprint(str(_all)) 2075 ### set __all__ for import * 2076 setattr(sys.modules[package_name], '__all__', _all) 2077 return members
Import all functions in a package to its __init__.
Parameters
- package (Optional[ModuleType], default None):
Package to import its functions into.
If
None(default), use parent. - package_name (Optional[str], default None): Name of package to import its functions into If None (default), use parent.
- types (Optional[List[str]], default None):
Types of members to return.
Defaults are
['method', 'builtin', 'class', 'function', 'package', 'module']
Returns
- A list of modules.
2081def reload_package( 2082 package: str, 2083 skip_submodules: Optional[List[str]] = None, 2084 lazy: bool = False, 2085 debug: bool = False, 2086 **kw: Any 2087): 2088 """ 2089 Recursively load a package's subpackages, even if they were not previously loaded. 2090 """ 2091 import sys 2092 if isinstance(package, str): 2093 package_name = package 2094 else: 2095 try: 2096 package_name = package.__name__ 2097 except Exception as e: 2098 package_name = str(package) 2099 2100 skip_submodules = skip_submodules or [] 2101 if 'meerschaum.utils.packages' not in skip_submodules: 2102 skip_submodules.append('meerschaum.utils.packages') 2103 def safeimport(): 2104 subs = [ 2105 m for m in sys.modules 2106 if m.startswith(package_name + '.') 2107 ] 2108 subs_to_skip = [] 2109 for skip_mod in skip_submodules: 2110 for mod in subs: 2111 if mod.startswith(skip_mod): 2112 subs_to_skip.append(mod) 2113 continue 2114 2115 subs = [m for m in subs if m not in subs_to_skip] 2116 for module_name in subs: 2117 _reload_module_cache[module_name] = sys.modules.pop(module_name, None) 2118 if not subs_to_skip: 2119 _reload_module_cache[package_name] = sys.modules.pop(package_name, None) 2120 2121 return _import_module(package_name) 2122 2123 return safeimport()
Recursively load a package's subpackages, even if they were not previously loaded.
2126def reload_meerschaum(debug: bool = False) -> SuccessTuple: 2127 """ 2128 Reload the currently loaded Meercshaum modules, refreshing plugins. 2129 """ 2130 reload_package( 2131 'meerschaum', 2132 skip_submodules = [ 2133 'meerschaum.utils.pool', 2134 ] 2135 ) 2136 2137 from meerschaum.plugins import reload_plugins 2138 reload_plugins(debug=debug) 2139 return True, "Success"
Reload the currently loaded Meercshaum modules, refreshing plugins.
2142def is_installed( 2143 import_name: str, 2144 venv: Optional[str] = 'mrsm', 2145 split: bool = True, 2146 allow_outside_venv: bool = True, 2147 debug: bool = False, 2148) -> bool: 2149 """ 2150 Check whether a package is installed. 2151 2152 Parameters 2153 ---------- 2154 import_name: str 2155 The import name of the module. 2156 2157 venv: Optional[str], default 'mrsm' 2158 The venv in which to search for the module. 2159 2160 split: bool, default True 2161 If `True`, split on periods to determine the root module name. 2162 2163 allow_outside_venv: bool, default True 2164 If `True`, search outside of the specified virtual environment 2165 if the package cannot be found. 2166 2167 Returns 2168 ------- 2169 A bool indicating whether a package may be imported. 2170 """ 2171 if debug: 2172 from meerschaum.utils.debug import dprint 2173 root_name = import_name.split('.')[0] if split else import_name 2174 import importlib.util 2175 with Venv(venv, debug=debug): 2176 try: 2177 spec_path = pathlib.Path( 2178 get_module_path(root_name, venv=venv, debug=debug) 2179 or 2180 ( 2181 importlib.util.find_spec(root_name).origin 2182 if venv is not None and allow_outside_venv 2183 else None 2184 ) 2185 ) 2186 except (ModuleNotFoundError, ValueError, AttributeError, TypeError) as e: 2187 spec_path = None 2188 2189 ### Whether the package is present, not whether it meets Meerschaum's minimum version: 2190 ### a too-old package is reported (`import_pandas()`, `attempt_import(check_update=True)`), 2191 ### never replaced by an implicit install. 2192 found = spec_path is not None 2193 2194 return found
Check whether a package is installed.
Parameters
- import_name (str): The import name of the module.
- venv (Optional[str], default 'mrsm'): The venv in which to search for the module.
- split (bool, default True):
If
True, split on periods to determine the root module name. - allow_outside_venv (bool, default True):
If
True, search outside of the specified virtual environment if the package cannot be found.
Returns
- A bool indicating whether a package may be imported.
2197def venv_contains_package( 2198 import_name: str, 2199 venv: Optional[str] = 'mrsm', 2200 split: bool = True, 2201 debug: bool = False, 2202) -> bool: 2203 """ 2204 Search the contents of a virtual environment for a package. 2205 """ 2206 import site 2207 import pathlib 2208 root_name = import_name.split('.')[0] if split else import_name 2209 return get_module_path(root_name, venv=venv, debug=debug) is not None
Search the contents of a virtual environment for a package.
2212def package_venv(package: 'ModuleType') -> Union[str, None]: 2213 """ 2214 Inspect a package and return the virtual environment in which it presides. 2215 """ 2216 import os 2217 import meerschaum.config.paths as paths 2218 if str(paths.VIRTENV_RESOURCES_PATH) not in package.__file__: 2219 return None 2220 return package.__file__.split(str(paths.VIRTENV_RESOURCES_PATH))[1].split(os.path.sep)[1]
Inspect a package and return the virtual environment in which it presides.
2223def ensure_readline() -> 'ModuleType': 2224 """Make sure that the `readline` package is able to be imported.""" 2225 import sys 2226 try: 2227 import readline 2228 except ImportError: 2229 readline = None 2230 2231 if readline is None: 2232 import platform 2233 rl_name = "gnureadline" if platform.system() != 'Windows' else "pyreadline3" 2234 try: 2235 rl = attempt_import( 2236 rl_name, 2237 lazy=False, 2238 install=True, 2239 venv=None, 2240 warn=False, 2241 ) 2242 except (ImportError, ModuleNotFoundError): 2243 if not pip_install( 2244 rl_name, 2245 args=['--upgrade', '--ignore-installed'], 2246 venv=None, 2247 _implicit=True, 2248 ): 2249 print(f"Unable to import {rl_name}!", file=sys.stderr) 2250 sys.exit(1) 2251 2252 sys.modules['readline'] = readline 2253 return readline
Make sure that the readline package is able to be imported.
2281def use_uv() -> bool: 2282 """ 2283 Return whether `uv` is available and enabled. 2284 """ 2285 from meerschaum.utils.misc import is_android 2286 if is_android(): 2287 return False 2288 2289 if not is_uv_enabled(): 2290 return False 2291 2292 return _get_uv_bin() is not None
Return whether uv is available and enabled.
2295def is_uv_enabled() -> bool: 2296 """ 2297 Return whether the user has disabled `uv`. 2298 """ 2299 from meerschaum.utils.misc import is_android 2300 if is_android(): 2301 return False 2302 2303 from meerschaum.config import get_config 2304 enabled = get_config('system', 'experimental', 'uv_pip') 2305 return enabled
Return whether the user has disabled uv.