Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
spawn.py131 linesDownload Raw Back to _distutils
1"""distutils.spawn2 3Provides the 'spawn()' function, a front-end to various platform-4specific functions for launching another program in a sub-process.5"""6 7from __future__ import annotations8 9import os10import platform11import shutil12import subprocess13import sys14import warnings15from collections.abc import Mapping, MutableSequence16from typing import TYPE_CHECKING, TypeVar, overload17 18from ._log import log19from .debug import DEBUG20from .errors import DistutilsExecError21 22if TYPE_CHECKING:23    from subprocess import _ENV24 25 26_MappingT = TypeVar("_MappingT", bound=Mapping)27 28 29def _debug(cmd):30    """31    Render a subprocess command differently depending on DEBUG.32    """33    return cmd if DEBUG else cmd[0]34 35 36def _inject_macos_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None:37    if platform.system() != 'Darwin':38        return env39 40    from .util import MACOSX_VERSION_VAR, get_macosx_target_ver41 42    target_ver = get_macosx_target_ver()43    update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {}44    return {**_resolve(env), **update}45 46 47@overload48def _resolve(env: None) -> os._Environ[str]: ...49@overload50def _resolve(env: _MappingT) -> _MappingT: ...51def _resolve(env: _MappingT | None) -> _MappingT | os._Environ[str]:52    return os.environ if env is None else env53 54 55def spawn(56    cmd: MutableSequence[bytes | str | os.PathLike[str]],57    search_path: bool = True,58    verbose: bool = False,59    env: _ENV | None = None,60) -> None:61    """Run another program, specified as a command list 'cmd', in a new process.62 63    'cmd' is just the argument list for the new process, ie.64    cmd[0] is the program to run and cmd[1:] are the rest of its arguments.65    There is no way to run a program with a name different from that of its66    executable.67 68    If 'search_path' is true (the default), the system's executable69    search path will be used to find the program; otherwise, cmd[0]70    must be the exact path to the executable.71 72    Raise DistutilsExecError if running the program fails in any way; just73    return on success.74    """75    log.info(subprocess.list2cmdline(cmd))76 77    if search_path:78        executable = shutil.which(cmd[0])79        if executable is not None:80            cmd[0] = executable81 82    try:83        subprocess.check_call(cmd, env=_inject_macos_ver(env))84    except OSError as exc:85        raise DistutilsExecError(86            f"command {_debug(cmd)!r} failed: {exc.args[-1]}"87        ) from exc88    except subprocess.CalledProcessError as err:89        raise DistutilsExecError(90            f"command {_debug(cmd)!r} failed with exit code {err.returncode}"91        ) from err92 93 94def find_executable(executable: str, path: str | None = None) -> str | None:95    """Tries to find 'executable' in the directories listed in 'path'.96 97    A string listing directories separated by 'os.pathsep'; defaults to98    os.environ['PATH'].  Returns the complete filename or None if not found.99    """100    warnings.warn(101        'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2102    )103    _, ext = os.path.splitext(executable)104    if (sys.platform == 'win32') and (ext != '.exe'):105        executable = executable + '.exe'106 107    if os.path.isfile(executable):108        return executable109 110    if path is None:111        path = os.environ.get('PATH', None)112        # bpo-35755: Don't fall through if PATH is the empty string113        if path is None:114            try:115                path = os.confstr("CS_PATH")116            except (AttributeError, ValueError):117                # os.confstr() or CS_PATH is not available118                path = os.defpath119 120    # PATH='' doesn't match, whereas PATH=':' looks in the current directory121    if not path:122        return None123 124    paths = path.split(os.pathsep)125    for p in paths:126        f = os.path.join(p, executable)127        if os.path.isfile(f):128            # the file exists, we have a shot at spawn working129            return f130    return None131 
codekingpro/portable-devtools · Team Ai