Home >Backend Development >Python Tutorial >How Do I Set the Default Python Version?
Historically, Python versions coexisted due to compatibility concerns. To maintain backwards compatibility, newer Python versions (e.g., Python 3) did not replace Python 2 when installed. This resulted in the confusing situation where typing "python" would invoke Python 2, even after installing Python 3.
However, modern systems encourage explicitly calling specific Python versions (e.g., "python2" or "python3") in scripts and commands.
To conveniently execute specific Python versions, create a shell alias. Here's an example for setting the default Python version to Python 3:
alias py=python3
The PATH environment variable controls which directories are searched for executable files. To prioritize specific Python versions, place the desired version's directory at the beginning of the path:
export PATH=/usr/local/bin/python3:$PATH
If multiple Python versions (e.g., Python 3.1 and 3.2) are installed, the PATH variable determines which version is executed. The first occurrence of a matching program in the specified directories will be invoked.
Here's an example where "python3" resolves to Python 3.7:
echo $PATH /usr/sbin:/usr/local/bin:/usr/sbin:usr/local/bin:/usr/bin:/bin which python3 /usr/bin/python3 ls -l /usr/bin/python3 lrwxrwxrwx 1 root root 9 Mar 26 2019 /usr/bin/python3 -> python3.7* ls -l /usr/bin/python3.7 -rwxr-xr-x 2 root root 4877888 Apr 2 2019 /usr/bin/python3.7*
To isolate specific Python versions and their packages, consider using virtual environments. This allows for customized installations and independent version management.
The above is the detailed content of How Do I Set the Default Python Version?. For more information, please follow other related articles on the PHP Chinese website!