杰瑞科技汇

Windows下Python 2与3如何共存?

Of course! This is a very common and important topic for developers using Windows. Here’s a comprehensive guide covering the differences, how to manage them, and best practices.

Windows下Python 2与3如何共存?-图1
(图片来源网络,侵删)

The Core Difference: Python 2 vs. Python 3

This is the most important distinction. Think of them as two different, incompatible versions of the same language.

Feature Python 2 (Legacy) Python 3 (Present & Future)
Status End-of-Life (EOL) since Jan 1, 2025. No longer receives updates, including security patches. Current Standard. Actively developed and maintained.
Print Statement print "Hello, World!" (is a statement) print("Hello, World!") (is a function)
Integer Division 5 / 2 results in 2 (truncates) 5 / 2 results in 5 (true division)
is for floor division. 5 // 2 results in 2. 5 // 2 results in 2.
Unicode Strings are bytes by default. Unicode support is clunky. Strings are unicode by default. bytes is a separate type.
input() vs raw_input() input() is dangerous (evaluates input). raw_input() is safe. input() is safe and behaves like raw_input() from Python 2.
Syntax for Exceptions except Exception, e: except Exception as e:
Library Support Many old libraries only work here. All new libraries are developed for Python 3. Many old libraries have been ported.
Future DO NOT USE FOR NEW PROJECTS. Only for maintaining old code. USE FOR ALL NEW PROJECTS.

Conclusion: You should always prefer Python 3 for any new work. You will only need Python 2 to maintain very old applications.


Installing Python on Windows

There are two main ways to install Python on Windows. The choice you make affects how you manage multiple versions.

Method 1: The Official Installer from python.org (Simple & Direct)

This is the most straightforward way, especially if you only need one version.

Windows下Python 2与3如何共存?-图2
(图片来源网络,侵删)
  1. Go to the Official Website: https://www.python.org/downloads/windows/

  2. Download the Installer:

    • For Python 3, download the latest stable release (e.g., Python 3.12.x).
    • For Python 2, you'll need to find an older version in the "All releases" section. Python 2.7.18 is the final version.
  3. Crucial Step During Installation:

    • Run the installer (.exe file).
    • VERY IMPORTANT: Check the box at the bottom that says "Add Python to PATH". This makes it easy to run Python from the Command Prompt without typing the full path.
  4. Complete the installation.

Method 2: Using a Version Manager (Advanced & Powerful)

A version manager is a tool that lets you easily install, switch between, and manage multiple Python versions side-by-side on your system. This is the recommended approach for serious developers.

Popular Windows Managers:

  • pyenv-win: A port of the popular pyenv tool for Windows. It's excellent and widely used.
  • conda: The package manager from the Anaconda/Miniconda distributions. It's not just a version manager but a full environment manager, which is fantastic for data science.

Example Workflow with pyenv-win:

  1. Installation:

    # Install pyenv-win using PowerShell
    Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1')
  2. Install Python Versions:

    • Open a new Command Prompt or PowerShell window (the PATH will have been updated).
    • Install Python 3.12:
      pyenv install 3.12.0
    • Install Python 2.7:
      pyenv install 2.7.18
  3. Switching Between Versions:

    • See what's installed:
      pyenv versions
      # * 2.7.18 (set by /Users/user/.python-version)
      #   3.12.0
    • Set a global default (the version you use most often):
      pyenv global 3.12.0
    • Set a version for just the current project directory:
      pyenv local 2.7.18

      This creates a .python-version file in your project. Whenever you cd into that directory, pyenv will automatically use Python 2.7.18.


How to Check Your Python Version

After installation, you need to verify it's working and check which version is active.

  1. Open Command Prompt or PowerShell.

  2. Check the Version:

    python --version
    # or
    python -V

    If you used the official installer and added to PATH, this should work.

  3. If You Have a Version Manager:

    • pyenv will automatically manage which python command points to. The command above will show the currently active version.
    • If you have both Python 2 and 3 installed via the official installer, the commands might conflict. In that case, the installer often creates aliases:
      • python -> Points to the default version (e.g., Python 3)
      • python3 -> Explicitly runs Python 3
      • python2 -> Explicitly runs Python 2

Managing Virtual Environments (Best Practice)

A virtual environment is an isolated space for a single project. It prevents package conflicts and keeps your global Python installation clean. You should always use a virtual environment.

For Python 3 (The Modern Way)

The venv module is built into Python 3.

  1. Navigate to your project folder:

    cd C:\path\to\my-project
  2. Create the environment:

    # Creates a folder named 'venv' in your project
    python -m venv venv

    If you have multiple versions, be explicit:

    python3 -m venv venv
  3. Activate the environment:

    .\venv\Scripts\activate

    Your command prompt will change to show (venv), indicating it's active.

  4. Work in the environment: Now, when you run pip install, it will install packages only into this venv.

  5. Deactivate the environment:

    deactivate

For Python 2 (The Old Way)

Python 2 does not have venv. You must use the virtualenv package.

  1. Install virtualenv (globally, or in a Python 3 environment):

    pip install virtualenv
  2. Navigate to your project folder:

    cd C:\path\to\my-old-project
  3. Create the environment:

    # Use 'python' to point to your Python 2 installation
    python -m virtualenv venv_py2
  4. Activate the environment:

    .\venv_py2\Scripts\activate

Summary and Recommendations

Your Goal Recommended Action
I'm a beginner / starting a new project. Install Python 3 from python.org (check "Add to PATH").
Use the built-in venv module for all projects.
I need to maintain old Python 2 code. Install Python 2.7.18 from python.org.
Use the virtualenv package for each Python 2 project to isolate dependencies.
Plan to migrate this code to Python 3.
I'm a developer working on many projects with different versions. Install a version manager like pyenv-win.
Install all the Python versions you need (2.7, 3.8, 3.11, etc.).
Use pyenv global for your default and pyenv local to set the version per project.
Still use venv inside each project for package isolation.
分享:
扫描分享到社交APP
上一篇
下一篇