search
HomeBackend DevelopmentPython TutorialHow to switch python2 and python3

How to switch python2 and python3

How to switch between python2 and python3? The switching methods are introduced below in the windows environment and Linux environment:

windows environment:

Install in the windows environment How to switch between python2 and python3? Use

to enter py -3 to enter python3

Enter py -2 to enter python2

Linux Environment:

#Why we need two versions of Python

Every developer who has come into contact with Python knows that Python2 and Python3 are incompatible Although Python3 is the future, there are still many projects developed using Python2. Many distributions of Linux (such as Ubuntu) come with Python 2.7, but when we are ready to develop a Python 3 project, what should we do?

Then download Python3 too. Well, it is indeed possible to install the two together under Linux, but the question is how do you switch between the two versions of Python.

1 Modify the alias

First let’s take a look at our default Python version

$ python --versionPython 2.7.6

Then we modify the alias

$ alias python='/usr/bin/python3'$ python --versionPython 3.4.3  # 版本已经改变

/usr/bin/python3 How was this path found?

Generally speaking, software binary files can be found in /usr/bin or /usr/local/bin (this one has a higher priority). Of course, if you are using Debian Linux, you can find it like this (provided you have installed Python3):

$ dpkg -L python3

The above alias modification is only temporary. , the configuration will disappear after reopening a window. If you want each window to use this alias, you can edit ~/.bashrc (if you are using another shell, it is not this file, such as zsh is ~/.zshrc) and write the alias configuration into the file.

The advantage of modifying the alias is that it is simple enough, but the switch is inflexible.

Related recommendations: "Python Video Tutorial"

2 Link file

Create a link in /usr/bin The file points to Python3.

$ ln -s python /usr/bin/python3$ python --versionPython 3.4.3

Just like modifying the alias, the modification is not flexible enough.

3 Use update-alternatives to switch versions

update-alternatives is a tool provided by Debian (you don’t need to read it if you are not a Debian system). The principle is similar to the one above The method is also through links, but the switching process is very convenient.

First take a look at the help information of update-alternatives:

$ update-alternatives --help
用法:update-alternatives [<选项> ...] <命令>
 
命令:
  --install <链接> <名称> <路径> <优先级>
    [--slave <链接> <名称> <路径>] ...
                           在系统中加入一组候选项。
  --remove <名称> <路径>   从 <名称> 替换组中去除 <路径> 项。
  --remove-all <名称>      从替换系统中删除 <名称> 替换组。
  --auto <名称>            将 <名称> 的主链接切换到自动模式。
  --display <名称>         显示关于 <名称> 替换组的信息。
  --query <名称>           机器可读版的 --display <名称>.
  --list <名称>            列出 <名称> 替换组中所有的可用候选项。
  --get-selections         列出主要候选项名称以及它们的状态。
  --set-selections         从标准输入中读入候选项的状态。
  --config <名称>          列出 <名称> 替换组中的可选项,并就使用其中
                           哪一个,征询用户的意见。
  --set <名称> <路径>      将 <路径> 设置为 <名称> 的候选项。
  --all                    对所有可选项一一调用 --config 命令。
 
<链接> 是指向 /etc/alternatives/<名称> 的符号链接。
    (如 /usr/bin/pager)
<名称> 是该链接替换组的主控名。
    (如 pager)
<路径> 是候选项目标文件的位置。
    (如 /usr/bin/less)
<优先级> 是一个整数,在自动模式下,这个数字越高的选项,其优先级也就越高。
 
选项:
  --altdir <目录>          改变候选项目录。
  --admindir <目录>        设置 statoverride 文件的目录。
  --log <文件>             改变日志文件。
  --force                  就算没有通过自检,也强制执行操作。
  --skip-auto              在自动模式中跳过设置正确候选项的提示
                           (只与 --config 有关)
  --verbose                启用详细输出。
  --quiet                  安静模式,输出尽可能少的信息。不显示输出信息。
  --help                   显示本帮助信息。
  --version                显示版本信息。

--install : Create a Group candidates

--config : Configure the options in the group and choose which one to use

--remove : Remove the option from

First let’s see if there are any options for Python:

$ update-alternatives --display pythonupdate-alternatives: 错误: 无 python 的候选项

Then first create python group, and add the options of Python2 and Python3

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2 # 添加Python2可选项,优先级为2
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.4 1 #添加Python3可选项,优先级为1

Note that in the /usr/bin/python link file here, the two options must be the same, so that this link file can select two Different options to link.

If we look at the file /usr/bin/python at this time, we will find that it is already linked to /etc/alternatives/python.

lrwxrwxrwx 1 root root        24  6月 19 18:39 python -> /etc/alternatives/python

Then let’s take a look at the version

$ python --version
Python 2.7.6

Why is it still Python2? Take a look at the configuration

$ sudo update-alternatives --config python
有 2 个候选项可用于替换 python (提供 /usr/bin/python)。   
选择         路径           优先级     状态
------------------------------------------------------------
* 0     /usr/bin/python2.7       2      自动模式  
  1     /usr/bin/python2.7       2      手动模式  
  2     /usr/bin/python3.4       1      手动模式
要维持当前值[*]请按回车键,或者键入选择的编号:

It turns out that it’s because the automatic mode is selected by default, and Python2 has a higher priority than Python3, just type 2 at this time to use Python3.

If you want to remove an option:

$ sudo update-alternatives --remove python /usr/bin/python2.7

update-alternatives only applies to Debian-based Linux.

4 virtualenvwrapper Switch version

virtualenvwrapper is a tool for managing Python virtual environments. It can easily create independent environments for different projects. Each project can be installed own dependencies, and also supports the existence of different versions of Python in different virtual environments.

First install virtualenvwrapper, you can choose apt installation or pip installation

apt installation

$ sudo apt-get install virtualenvwrapper

pip installation

$ sudo pip install virtualenvwrapper

When you need to use Python2 to develop projects, Create a Python2 virtual environment:

$ mkvirtualenv -p /usr/bin/python2 env27

When you need Python3 development:

$ mkvirtualenv -p /usr/bin/python3.4 env34

Then you can switch to different virtual environments at any time:

$ workon env27  # 进入Python2环境$ workon env34  # 进入Python3环境

It’s more fun Yes, you can switch to the project directory while entering the virtual environment. You only need to edit the file $VIRTUAL_ENV/bin/postactivate:

$ vim $VIRTUAL_ENV/bin/postactivate  #前提是已经进入对应的虚拟环境

Add the command to switch directories in the file:

cd  /path/to/your/project

5 Summary

The first two methods are not recommended.

Using update-alternatives to switch versions is only applicable to Debian-based Linux.

It is recommended to use virtualenvwrapper to manage virtual environments and versions.

The above is the detailed content of How to switch python2 and python3. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft