Exemple #1
0
def commands():
    import os
    import virtualenv
    from pythonfinder import Finder

    finder = Finder()
    python_exec = finder.find_python_version(this.version.major,
                                             minor=this.version.minor)
    if python_exec is None:
        stop("No python installed in system.")

    venv_dir = python_exec.path.parent / "rez.venv"

    args = [
        "--python",
        str(python_exec.path),
        "--no-seed",  # no pip, no wheel, no setuptools
        str(venv_dir)
    ]

    # compute venv
    session = virtualenv.session_via_cli(args)

    if not os.path.isdir(str(session.creator.bin_dir)):
        print("\tCreating virtual env..")
        session = virtualenv.cli_run(args)

    env.PATH.prepend(str(session.creator.bin_dir))
Exemple #2
0
def _get_python_versions():
    finder = Finder(global_search=True, system=False, ignore_unsupported=True)
    pythons = finder.find_all_python_versions()
    for v in pythons:
        py = v.py_version
        comes_from = getattr(py, "comes_from", None)
        if comes_from is not None:
            comes_from_path = getattr(comes_from, "path", v.path)
        else:
            comes_from_path = v.path
    return sorted(list(pythons))
Exemple #3
0
    def python_executable(self) -> str:
        """Get the Python interpreter path."""
        config = self.config
        if self.project_config.get(
                "python.path") and not os.getenv("PDM_IGNORE_SAVED_PYTHON"):
            return self.project_config["python.path"]
        path = None
        if config["use_venv"]:
            path = get_venv_python(self.root)
            if path:
                stream.echo(
                    f"Virtualenv interpreter {stream.green(path)} is detected.",
                    err=True,
                    verbosity=stream.DETAIL,
                )
        if not path and PYENV_INSTALLED and config.get("python.use_pyenv",
                                                       True):
            path = Path(PYENV_ROOT, "shims", "python").as_posix()
        if not path:
            path = shutil.which("python")

        version = None
        if path:
            try:
                version, _ = get_python_version(path, True)
            except (FileNotFoundError, subprocess.CalledProcessError):
                version = None
        if not version or not self.python_requires.contains(version):
            finder = Finder()
            for python in finder.find_all_python_versions():
                version, _ = get_python_version(python.path.as_posix(), True)
                if self.python_requires.contains(version):
                    path = python.path.as_posix()
                    break
            else:
                version = ".".join(map(str, sys.version_info[:3]))
                if self.python_requires.contains(version):
                    path = sys.executable
        if path:
            if os.path.normcase(path) == os.path.normcase(sys.executable):
                # Refer to the base interpreter to allow for venvs
                path = getattr(sys, "_base_executable", sys.executable)
            stream.echo(
                "Using Python interpreter: {} ({})".format(
                    stream.green(path), version),
                err=True,
            )
            if not os.getenv("PDM_IGNORE_SAVED_PYTHON"):
                self.project_config["python.path"] = Path(path).as_posix()
            return path
        raise NoPythonVersion(
            "No Python that satisfies {} is found on the system.".format(
                self.python_requires))
Exemple #4
0
def versions():
    from pythonfinder import Finder
    return [
        # e.g. "2.7-venv"
        py.py_version.name + "-venv"
        for py in Finder().find_all_python_versions()
    ]
Exemple #5
0
    def find_interpreters(self,
                          python_spec: str | None = None
                          ) -> Iterable[PythonInfo]:
        """Return an iterable of interpreter paths that matches the given specifier,
        which can be:
            1. a version specifier like 3.7
            2. an absolute path
            3. a short name like python3
            4. None that returns all possible interpreters
        """
        config = self.config
        python: str | Path | None = None

        if not python_spec:
            if config.get("python.use_pyenv", True) and PYENV_INSTALLED:
                pyenv_shim = os.path.join(PYENV_ROOT, "shims", "python3")
                if os.path.exists(pyenv_shim):
                    yield PythonInfo.from_path(pyenv_shim)
                elif os.path.exists(pyenv_shim[:-1]):
                    yield PythonInfo.from_path(pyenv_shim[:-1])
            if config.get("use_venv"):
                python = get_in_project_venv_python(self.root)
                if python:
                    yield PythonInfo.from_path(python)
            python = shutil.which("python")
            if python:
                yield PythonInfo.from_path(python)
            args = []
        else:
            if not all(c.isdigit() for c in python_spec.split(".")):
                if Path(python_spec).exists():
                    python = find_python_in_path(python_spec)
                    if python:
                        yield PythonInfo.from_path(python)
                else:
                    python = shutil.which(python_spec)
                    if python:
                        yield PythonInfo.from_path(python)
                return
            args = [int(v) for v in python_spec.split(".") if v != ""]
        finder = Finder()
        for entry in finder.find_all_python_versions(*args):
            yield PythonInfo.from_python_version(entry.py_version)
        if not python_spec:
            this_python = getattr(sys, "_base_executable", sys.executable)
            yield PythonInfo.from_path(this_python)
Exemple #6
0
    def python_executable(self) -> str:
        """Get the Python interpreter path."""
        config = self.project.config
        if config.get("python.path"):
            return config["python.path"]
        if PYENV_INSTALLED and config.get("python.use_pyenv", True):
            return os.path.join(PYENV_ROOT, "shims", "python")
        if "VIRTUAL_ENV" in os.environ:
            stream.echo(
                "An activated virtualenv is detected, reuse the interpreter now.",
                err=True,
                verbosity=stream.DETAIL,
            )
            return get_venv_python(self.project.root)

        # First try what `python` refers to.
        path = shutil.which("python")
        version = None
        if path:
            version, _ = get_python_version(path, True)
        if not version or not self.python_requires.contains(version):
            finder = Finder()
            for python in finder.find_all_python_versions():
                version, _ = get_python_version(python.path.as_posix(), True)
                if self.python_requires.contains(version):
                    path = python.path.as_posix()
                    break
            else:
                version = ".".join(map(str, sys.version_info[:3]))
                if self.python_requires.contains(version):
                    path = sys.executable
        if path:
            stream.echo(
                "Using Python interpreter: {} ({})".format(stream.green(path), version)
            )
            self.project.project_config["python.path"] = Path(path).as_posix()
            return path
        raise NoPythonVersion(
            "No Python that satisfies {} is found on the system.".format(
                self.python_requires
            )
        )
Exemple #7
0
    def python_executable(self) -> str:
        """Get the Python interpreter path."""
        path = None
        if self.config["python"]:
            path = self.config["python"]
            try:
                get_python_version(path)
                return path
            except Exception:
                pass

        path = None
        version = None
        # First try what `python` refers to.
        path = shutil.which("python")
        if path:
            version = get_python_version(path, True)
        else:
            finder = Finder()
            for python in finder.find_all_python_versions():
                version = ".".join(
                    map(str, get_python_version(python.path.as_posix())))
                if self.python_requires.contains(version):
                    path = python.path.as_posix()
                    break
            else:
                version = ".".join(map(str, sys.version_info[:3]))
                if self.python_requires.contains(version):
                    path = sys.executable
        if path:
            context.io.echo("Using Python interpreter: {} ({})".format(
                context.io.green(path), version))
            self.config["python"] = Path(path).as_posix()
            self.config.save_config()
            return path
        raise NoPythonVersion(
            "No Python that satisfies {} is found on the system.".format(
                self.python_requires))
Exemple #8
0
    def python_executable(self) -> str:
        """Get the Python interpreter path."""
        if self.config.get("python.path"):
            path = self.config["python.path"]
            try:
                get_python_version(path)
                return path
            except Exception:
                pass
        if PYENV_INSTALLED and self.config.get("python.use_pyenv", True):
            return os.path.join(PYENV_ROOT, "shims", "python")

        # First try what `python` refers to.
        path = shutil.which("python")
        version = None
        if path:
            version = get_python_version(path, True)
        if not version or not self.python_requires.contains(version):
            finder = Finder()
            for python in finder.find_all_python_versions():
                version = get_python_version(python.path.as_posix(), True)
                if self.python_requires.contains(version):
                    path = python.path.as_posix()
                    break
            else:
                version = ".".join(map(str, sys.version_info[:3]))
                if self.python_requires.contains(version):
                    path = sys.executable
        if path:
            context.io.echo("Using Python interpreter: {} ({})".format(
                context.io.green(path), version))
            self.config["python.path"] = Path(path).as_posix()
            self.config.save_config()
            return path
        raise NoPythonVersion(
            "No Python that satisfies {} is found on the system.".format(
                self.python_requires))