Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Simple Python version management

License

NotificationsYou must be signed in to change notification settings

pyenv/pyenv

Repository files navigation

Join the chat at https://gitter.im/yyuu/pyenv

pyenv lets you easily switch between multiple versions of Python. It'ssimple, unobtrusive, and follows the UNIX tradition of single-purposetools that do one thing well.

This project was forked fromrbenv andruby-build, and modified for Python.

What pyenvdoes...

  • Lets youchange the global Python version on a per-user basis.
  • Provides support forper-project Python versions.
  • Allows you tooverride the Python version with an environmentvariable.
  • Searches for commands frommultiple versions of Python at a time.This may be helpful to test across Python versions withtox.

In contrast with pythonbrew and pythonz, pyenvdoes not...

  • Depend on Python itself. pyenv was made from pure shell scripts.There is no bootstrap problem of Python.
  • Need to be loaded into your shell. Instead, pyenv's shimapproach works by adding a directory to yourPATH.
  • Manage virtualenv. Of course, you can createvirtualenvyourself, orpyenv-virtualenvto automate the process.

Table of Contents


Installation

A. Getting Pyenv


Linux/Unix

The Homebrew option from theMacOS section below would also work if you have Homebrew installed.

1. Automatic installer (Recommended)
curl -fsSL https://pyenv.run| bash

For more details visit our other project:https://github.com/pyenv/pyenv-installer

2. Basic GitHub Checkout

This will get you going with the latest version of Pyenv and make iteasy to fork and contribute any changes back upstream.

  • Check out Pyenv where you want it installed.A good place to choose is$HOME/.pyenv (but you can install it somewhere else):
    git clone https://github.com/pyenv/pyenv.git ~/.pyenv
  • Optionally, try to compile a dynamic Bash extension to speed up Pyenv. Don'tworry if it fails; Pyenv will still work normally:
    cd ~/.pyenv && src/configure && make -C src

MacOS

The options from theLinux section above also work but Homebrew is recommended for basic usage.

Homebrew in macOS
  1. Update homebrew and install pyenv:

    brew updatebrew install pyenv

    If you want to install (and update to) the latest development head of Pyenvrather than the latest release, instead run:

    brew install pyenv --head
  2. Then follow the rest of the post-installation steps, starting withSet up your shell environment for Pyenv.

  3. OPTIONAL. To fixbrew doctor's warning""config" scripts exist outside your system or Homebrew directories"

    If you're going to build Homebrew formulae from source that link against Pythonlike Tkinter or NumPy(This is only generally the case if you are a developer of such a formula,or if you have an EOL version of MacOS for which prebuilt bottles are no longer providedand you are using such a formula).

    To avoid them accidentally linking against a Pyenv-provided Python,add the following line into your interactive shell's configuration:

    • Bash/Zsh:

      alias brew='env PATH="${PATH//$(pyenv root)\/shims:/}" brew'
    • Fish:

      alias brew="env PATH=(string replace (pyenv root)/shims ''\"\$PATH\") brew"

Windows

Pyenv does not officially support Windows and does not work in Windows outsidethe Windows Subsystem for Linux.Moreover, even there, the Pythons it installs are not native Windows versionsbut rather Linux versions running in a virtual machine --so you won't get Windows-specific functionality.

If you're in Windows, we recommend using @kirankotari'spyenv-win fork --which does install native Windows Python versions.

B. Set up your shell environment for Pyenv


The below setup should work for the vast majority of users for common use cases.SeeAdvanced configuration for details and more configuration options.

Bash

Stock Bash startup files vary widely between distributions in which of them sourcewhich, under what circumstances, in what order and what additional configuration they perform.As such, the most reliable way to get Pyenv in all environments is to append Pyenvconfiguration commands to both.bashrc (for interactive shells)and the profile file that Bash would use (for login shells).

  1. First, add the commands to~/.bashrc by running the following in your terminal:

    echo'export PYENV_ROOT="$HOME/.pyenv"'>>~/.bashrcecho'[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"'>>~/.bashrcecho'eval "$(pyenv init - bash)"'>>~/.bashrc
  2. Then, if you have~/.profile,~/.bash_profile or~/.bash_login, add the commands there as well.If you have none of these, create a~/.profile and add the commands there.

    • to add to~/.profile:
      echo'export PYENV_ROOT="$HOME/.pyenv"'>>~/.profileecho'[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"'>>~/.profileecho'eval "$(pyenv init - bash)"'>>~/.profile
    • to add to~/.bash_profile:
      echo'export PYENV_ROOT="$HOME/.pyenv"'>>~/.bash_profileecho'[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"'>>~/.bash_profileecho'eval "$(pyenv init - bash)"'>>~/.bash_profile

Bash warning: There are some systems where theBASH_ENV variable is configuredto point to.bashrc. On such systems, you should almost certainly put theeval "$(pyenv init - bash)" line into.bash_profile, andnot into.bashrc. Otherwise, youmay observe strange behaviour, such aspyenv getting into an infinite loop.See#264 for details.

Zsh

echo'export PYENV_ROOT="$HOME/.pyenv"'>>~/.zshrcecho'[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"'>>~/.zshrcecho'eval "$(pyenv init - zsh)"'>>~/.zshrc

If you wish to get Pyenv in noninteractive login shells as well, also add the commands to~/.zprofile or~/.zlogin.

Fish

  1. If you have Fish 3.2.0 or newer, execute this interactively:

    set-Ux PYENV_ROOT$HOME/.pyenv  fish_add_path$PYENV_ROOT/bin
  2. Otherwise, execute the snippet below:

    set-Ux PYENV_ROOT$HOME/.pyenvset-U fish_user_paths$PYENV_ROOT/bin$fish_user_paths
  3. Now, add this to~/.config/fish/config.fish:

      pyenv init - fish| source

C. Restart your shell


for thePATH changes to take effect.

exec"$SHELL"

D. Install Python build dependencies


Install Python build dependenciesbefore attempting to install a new Python version.

You can now begin using Pyenv.

E. Upgrade Notes


if you have upgraded from pyenv version 2.0.x-2.2.x

The startup logic and instructions have been updated for simplicity in 2.3.0.The previous, more complicated configuration scheme for 2.0.0-2.2.5 still works.

  • Define environment variablePYENV_ROOT to point to the path wherePyenv will store its data.$HOME/.pyenv is the default.If you installed Pyenv via Git checkout, we recommendto set it to the same location as where you cloned it.
  • Add thepyenv executable to yourPATH if it's not already there
  • runeval "$(pyenv init -)" to installpyenv into your shell as a shell function, enable shims and autocompletion
    • You may runeval "$(pyenv init --path)" instead to just enable shims, without shell integration

Usage

Terminal output example

Install additional Python versions

To install additional Python versions, usepyenv install.

For example, to download and install Python 3.10.4, run:

pyenv install 3.10.4

Runningpyenv install -l gives the list of all available versions.


Notes about python releases

NOTE: Most Pyenv-provided Python releases are source releases and are builtfrom source as part of installation (that's why you need Python build dependencies preinstalled).You can pass options to Python'sconfigure and compiler flags to customize the build,seeSpecial environment variables in Python-Build's READMEfor details.

NOTE: If you are having trouble installing a Python version,please visit the wiki page aboutCommon Build Problems.

NOTE: If you want to use proxy for download, please set thehttp_proxy andhttps_proxyenvironment variables.

NOTE: If you'd like a faster interpreter at the cost of longer build times,seeBuilding for maximum performance in Python-Build's README.


Prefix auto-resolution to the latest version

All Pyenv subcommands exceptuninstall automatically resolve full prefixes to the latest version in the corresponding version line.

pyenv install picks the latest known version, while other subcommands pick the latest installed version.

E.g. to install and then switch to the latest 3.10 release:

pyenv install 3.10pyenv global 3.10

You can runpyenv latest -k <prefix> to see howpyenv install would resolve a specific prefix, orpyenv latest <prefix> to see how other subcommands would resolve it.

See thepyenv latest documentation for details.

Python versions with extended support

For the following Python releases, Pyenv applies user-provided patches that add support for some newer environments.Though we don't actively maintain those patches, since existing releases never change,it's safe to assume that they will continue working until there are further incompatible changesin a later version of those environments.

  • 3.7.8-3.7.15, 3.8.4-3.8.12, 3.9.0-3.9.7 : XCode 13.3
  • 3.5.10, 3.6.15 : MacOS 11+ and XCode 13.3
  • 2.7.18 : MacOS 10.15+ and Apple Silicon

Switch between Python versions

To select a Pyenv-installed Python as the version to use, run oneof the following commands:

E.g. to select the above-mentioned newly-installed Python 3.10.4 as your preferred version to use:

pyenv global 3.10.4

Now whenever you invokepython,pip etc., an executable from the Pyenv-provided3.10.4 installation will be run instead of the system Python.

Using "system" as a version name would reset the selection to your system-provided Python.

SeeUnderstanding shims andUnderstanding Python version selectionfor more details on how the selection works and more information on its usage.


Making multiple versions available

You can select multiple Python versions at the same time by specifying multiple arguments.E.g. if you wish to use the latest installed CPython 3.11 and 3.12:

pyenv global 3.11 3.12

Whenever you run a command provided by a Python installation, these versions will be searched for it in the specified order.Due to the shims' fall-through behavior,system is always implicitly searched afterwards.


Uninstall Python versions

As time goes on, you will accumulate Python versions in your$(pyenv root)/versions directory.

To remove old Python versions, usepyenv uninstall <versions>.

Alternatively, you can simplyrm -rf the directory of the version you wantto remove. You can find the directory of a particular Python versionwith thepyenv prefix command, e.g.pyenv prefix 2.6.8.Note however that plugins may run additional operations on uninstallwhich you would need to do by hand as well. E.g. Pyenv-Virtualenv alsoremoves any virtual environments linked to the version being uninstalled.


Other operations

Runpyenv commands to get a list of all available subcommands.Run a subcommand with--help to get help on it, or see theCommands Reference.

Note that Pyenv plugins that you install may add their own subcommands.

Upgrading

Upgrading with Homebrew

If you've installed Pyenv using Homebrew, upgrade using:

brew upgrade pyenv

To switch from a release to the latest development head of Pyenv, use:

brew uninstall pyenvbrew install pyenv --head

then you can upgrade it withbrew upgrade pyenv as usual.

Upgrading with Installer or Git checkout

If you've installed Pyenv with Pyenv-installer, you likely have thePyenv-Update plugin that wouldupgrade Pyenv and all installed plugins:

pyenv update

If you've installed Pyenv using Pyenv-installer or Git checkout, you can alsoupgrade your installation at any time using Git.

To upgrade to the latest development version of pyenv, usegit pull:

cd$(pyenv root)git pull

To upgrade to a specific release of Pyenv, check out the corresponding tag:

cd$(pyenv root)git fetchgit taggit checkout v0.1.0

Uninstalling pyenv

The simplicity of pyenv makes it easy to temporarily disable it, oruninstall from the system.

  1. Todisable Pyenv managing your Python versions, simply remove thepyenv init invocations from your shell startup configuration. This willremove Pyenv shims directory fromPATH, and future invocations likepython will execute the system Python version, as it was before Pyenv.

    pyenv will still be accessible on the command line, but your Pythonapps won't be affected by version switching.

  2. To completelyuninstall Pyenv, removeall Pyenv configuration linesfrom your shell startup configuration, and then removeits root directory. This willdelete all Python versions that wereinstalled under the$(pyenv root)/versions/ directory:

    rm -rf$(pyenv root)

    If you've installed Pyenv using a package manager, as a final step,perform the Pyenv package removal. For instance, for Homebrew:

    brew uninstall pyenv

Pyenv plugins

Pyenv provides a simple way to extend and customize its functionality with plugins --as simple as creating a plugin directory and dropping a shell script on a certain subpath of itwith whatever extra logic you need to be run at certain moments.

The main idea is that most things that you can put under$PYENV_ROOT/<whatever> you can also putunder$PYENV_ROOT/plugins/your_plugin_name/<whatever>.

SeePlugins on the wiki on how to install and use pluginsas well as a catalog of some useful existing plugins for common needs.

SeeAuthoring plugins on the wiki on writing your own plugins.


How It Works

At a high level, pyenv intercepts Python commands using shimexecutables injected into yourPATH, determines which Python versionhas been specified by your application, and passes your commands alongto the correct Python installation.

Understanding PATH

When you run a command likepython orpip, your shell (bash / zshrc / ...)searches through a list of directories to find an executable file withthat name. This list of directories lives in an environment variablecalledPATH, with each directory in the list separated by a colon:

/usr/local/bin:/usr/bin:/bin

Directories inPATH are searched from left to right, so a matchingexecutable in a directory at the beginning of the list takesprecedence over another one at the end. In this example, the/usr/local/bin directory will be searched first, then/usr/bin,then/bin.

Understanding Shims

pyenv works by inserting a directory ofshims at the front of yourPATH:

$(pyenv root)/shims:/usr/local/bin:/usr/bin:/bin

Through a process calledrehashing, pyenv maintains shims in thatdirectory to match every Python command across every installed versionof Python—python,pip, and so on.

Shims are lightweight executables that simply pass your command alongto pyenv. So with pyenv installed, when you run, say,pip, youroperating system will do the following:

  • Search yourPATH for an executable file namedpip
  • Find the pyenv shim namedpip at the beginning of yourPATH
  • Run the shim namedpip, which in turn passes the command along topyenv

Understanding Python version selection

When you execute a shim, pyenv determines which Python version to use byreading it from the following sources, in this order:

  1. ThePYENV_VERSION environment variable (if specified). You can usethepyenv shell command to set this environmentvariable in your current shell session.

  2. The application-specific.python-version file in the currentdirectory (if present). You can modify the current directory's.python-version file with thepyenv localcommand.

  3. The first.python-version file found (if any) by searching each parentdirectory, until reaching the root of your filesystem.

  4. The global$(pyenv root)/version file. You can modify this file usingthepyenv global command.If the global version file is not present, pyenv assumes you want to use the "system"Python (see below).

A special version name "system" means to use whatever Python is found onPATHafter the shimsPATH entry (in other words, whatever would be run if Pyenvshims weren't onPATH). Note that Pyenv considers those installations outsideits control and does not attempt to inspect or distinguish them in any way.So e.g. if you are on MacOS and have OS-bundled Python 3.8.9 and Homebrew-installedPython 3.9.12 and 3.10.2 -- for Pyenv, this is still a single "system" version,and whichever of those is first onPATH under the executable name youspecified will be run.

NOTE: You can activate multiple versions at the same time, including multipleversions of Python2 or Python3 simultaneously. This allows for parallel usage ofPython2 and Python3, and is required with tools liketox. For example, to instructPyenv to first use your system Python and Python3 (which are e.g. 2.7.9 and 3.4.2)but also have Python 3.3.6, 3.2.1, and 2.5.2 available, you firstpyenv installthe missing versions, then setpyenv global system 3.3.6 3.2.1 2.5.2.Then you'll be able to invoke any of those versions with an appropriatepythonX orpythonX.Y name.You can also specify multiple versions in a.python-version file by hand,separated by newlines. Lines starting with a# are ignored.

pyenv which <command> displays which real executable would berun when you invoke<command> via a shim.E.g. if you have 3.3.6, 3.2.1 and 2.5.2 installed of which 3.3.6 and 2.5.2 are selectedand your system Python is 3.2.5,pyenv which python2.5 should display$(pyenv root)/versions/2.5.2/bin/python2.5,pyenv which python3 --$(pyenv root)/versions/3.3.6/bin/python3 andpyenv which python3.2 -- path to your system Python due to the fall-through (see below).

Shims also fall through to anything further onPATH if the corresponding executable isnot present in any of the selected Python installations.This allows you to use any programs installed elsewhere on the system as long asthey are not shadowed by a selected Python installation.

Locating Pyenv-provided Python installations

Once pyenv has determined which version of Python your application hasspecified, it passes the command along to the corresponding Pythoninstallation.

Each Python version is installed into its own directory under$(pyenv root)/versions.

For example, you might have these versions installed:

  • $(pyenv root)/versions/2.7.8/
  • $(pyenv root)/versions/3.4.2/
  • $(pyenv root)/versions/pypy-2.4.0/

As far as Pyenv is concerned, version names are simply directories under$(pyenv root)/versions.


Advanced Configuration

Skip this section unless you must know what every line in your shellprofile is doing.

Also see theEnvironment variables sectionfor the environment variables that control Pyenv's behavior.

pyenv init is the only command that crosses the line of loadingextra commands into your shell. Coming from RVM, some of you might beopposed to this idea. Here's whateval "$(pyenv init -)" actually does:

  1. Finds current shell.pyenv init figures out what shell you are using, as the exact commands ofeval "$(pyenv init -)" vary depending on shell. Specifying which shell you are using (e.g.eval "$(pyenv init - bash)") is preferred, because it reduces launch time significantly.

  2. Sets up the shims path. This is what allows Pyenv to interceptand redirect invocations ofpython,pip etc. transparently.It prepends$(pyenv root)/shims to your$PATH.It also deletes any other instances of$(pyenv root)/shims onPATHwhich allows to invokeeval "$(pyenv init -)" multiple times withoutgetting duplicatePATH entries.

  3. Installs autocompletion. This is entirely optional but prettyuseful. Sourcing<pyenv installation prefix>/completions/pyenv.bash will set thatup. There are also completions for Zsh and Fish.

  4. Rehashes shims. From time to time you'll need to rebuild yourshim files. Doing this on init makes sure everything is up todate. You can always runpyenv rehash manually.

  5. Installspyenv into the current shell as a shell function.This bit is also optional, but allowspyenv and plugins to change variables in your current shell.This is required for some commands likepyenv shell to work.The sh dispatcher doesn't doanything crazy like overridecd or hack your shell prompt, but iffor some reason you needpyenv to be a real script rather than ashell function, you can safely skip it.

eval "$(pyenv init --path)" only does items 2 and 4.

To see exactly what happens under the hood for yourself, runpyenv init -orpyenv init --path.

eval "$(pyenv init -)" is supposed to run at any interactive shell'sstartup (including nested shells -- e.g. those invoked from editors)so that you get completion and convenience shell functions.

eval "$(pyenv init --path)" can be used instead ofeval "$(pyenv init -)"to just enable shims, without shell integration. It can also be used to bump shimsto the front ofPATH after some other logic has prepended stuff toPATHthat may shadow Pyenv's shims.

  • In particular, in Debian-based distributions, the stock~/.profileprepends per-userbin directories toPATH after having sourced~/.bashrc.This necessitates appending apyenv init call to~/.profile as well as~/.bashrcin these distributions because the system's Pip places executables formodules installed by a non-root user into those per-userbin directories.

Using Pyenv without shims

If you don't want to usepyenv init and shims, you can still benefitfrom pyenv's ability to install Python versions for you. Just runpyenv install and you will find versions installed in$(pyenv root)/versions.

You can manually execute or symlink them as required,or you can usepyenv exec <command>whenever you want<command> to be affected by Pyenv's version selectionas currently configured.

pyenv exec works by prepending$(pyenv root)/versions/<selected version>/bintoPATH in the<command>'s environment, the same as what e.g. RVM does.

Environment variables

You can affect how Pyenv operates with the following environment variables:

namedefaultdescription
PYENV_VERSIONSpecifies the Python version to be used.
Also seepyenv shell
PYENV_ROOT~/.pyenvDefines the directory under which Python versions and shims reside.
Also seepyenv root
PYENV_DEBUGOutputs debug information.
Also as:pyenv --debug <subcommand>
PYENV_HOOK_PATHsee wikiColon-separated list of paths searched for pyenv hooks.
PYENV_DIR$PWDDirectory to start searching for.python-version files.

See alsoSpecial environment variables in Python-Build's READMEfor environment variables that can be used to customize the build.


Development

The pyenv source code ishosted onGitHub. It's clean, modular,and easy to understand, even if you're not a shell hacker.

Tests are executed usingBats:

bats testbats/test/<file>.bats

Contributing

Feel free to submit pull requests and file bugs on theissuetracker.

SeeCONTRIBUTING.md for more details on submitting changes.

Version History

SeeCHANGELOG.md.

License

The MIT License


[8]ページ先頭

©2009-2025 Movatter.jp