Python has been evolving for nearly 10 years, so the development of Python projects also needs to consider the issue of version.
Especially now that Python 2 has retired, most Python projects now use Python 3 as the main version, but some of the old projects in companies still use Python 2 for development, so developers must switch between Python 2 and 3.
If you have trouble switching between Python versions, then pyenv will be your best friend!
This article’s environment
It is very easy to install pyenv on macOS via homebrew:
$ brew install pyenv
After the installation of pyenv is complete, please run the following command for the subsequent configuration:
$ pyenv init
After successful execution, the following prompt will appear, telling us that we need to add the following lines to
~/.zshrc to enable pyenv:
export PYENV_ROOT="$HOME/.pyenv" command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)"
The above settings will automatically enable pyenv after logging in to the system.
pyenv init will automatically detect the shell environment you are using; if you are using bash, it will prompt you to modify
.bash_profile instead of
Once the settings are completed, execute the following commands to restart the SHELL, and make the pyenv settings take effect:
$ exec "$SHELL"
That’s it for the setup!
How to use pyenv
Pyenv is a tool to help us switch Python versions conveniently, so we can use the following command to list which versions of Python we are using currently:
$ pyenv versions * system
Since we have not installed other versions of Python, the result of the above command is only
system, which is the system default version.
So what versions of pyenv are available to install? You can list them out with the following command:
$ pyenv install --list ... 3.6.9 3.7.0 3.7-dev 3.7.1 3.7.2 ...
After checking the version, you can install the latest version, such as Python 3.11.1, with the following command:
$ pyenv install 3.11.1
After success, run
pyenv versions again, and you will find 3.11.1 added.
$ pyenv versions * system 3.11.1
Then use the following command to switch the system’s default Python version to 3.11.1:
$ pyenv global 3.11.1
You can use the following command to verify that you have switched to Python 3.11.1:
$ python --version Python 3.11.1
If you want to specify a Python version for a certain folder, you can use the
pyenv local <version> command in that folder to specify the version. This command will create a
.python-version file in that folder. If you enter the folder in the future, pyenv will automatically switch the Python version according to the content of
.python-version, for example:
$ cd my-python-3.10.9-project $ pyenv local 3.10.9 $ python --version Python 3.10.9
Above is the usage of pyenv, if you are interested in further understanding pyenv, you can go to pyenv GitHub to read more official documents.