有些急性子

有些急性子

有些急性子
jike

AI Programming Essentials - Complete Guide to Virtual Environments

Can AI code run today and crash tomorrow? Set up a virtual environment in 5 minutes#


You must have encountered this problem#

Yesterday, you had ChatGPT write a data analysis script, and it ran perfectly.

Today, you asked AI to write a web scraping project and installed a new version of pandas.

As a result, yesterday's data analysis script suddenly reported an error:

AttributeError: 'DataFrame' object has no attribute 'append'

You were confused: I didn't change anything, why can't it run?


The problem lies here: the new project requires pandas 2.0, and you upgraded pandas in your system using pip install.

But the old project was written based on pandas 1.5, and pandas 2.0 removed the .append() method.

The system can only have one version installed; the new project can run, but the old project crashes.


This article will tell you:

  • Why this "whack-a-mole" problem occurs
  • How professional developers solve it (virtual environments)
  • Learn to manage virtual environments with the uv tool in 5 minutes
  • 3 common pitfalls for beginners

Reading time: 8 minutes
Practical time: 5 minutes
Prerequisite: You have Python installed and can run simple code


Chapter 1: Why do your projects "fight" each other?#

Dependency conflict illustration

The essence of the problem#

You have a system Python environment on your computer, where all libraries installed with pip install are stored.

C:\Python\Lib\site-packages\
├─ pandas (only one version can be installed!)
├─ numpy
└─ requests

When you work on multiple projects, the problem arises:

Scenario 1:

  • Project A (data analysis written 3 months ago): requires pandas 1.5
  • Project B (web scraper written today): requires pandas 2.0

You installed pandas 2.0, which overwrote the 1.5 version in the system.


Scenario 2:

  • Project C: AI chatbot, using the openai library
  • Project D: Image processing, using pillow and opencv

Three months later, you want to rerun Project C but forgot which libraries you installed back then.

There are 50 libraries in the system environment, and you don't know which ones are needed for Project C.


Scenario 3:

You send the code to a colleague, and they ask, "What libraries do I need to install?"

You reply, "Uh... pandas, numpy, requests... what else?"

Your colleague installs as you said, but the versions are wrong, and the code still throws an error.


The root of the problem#

System environment = public wardrobe

Everyone (all projects) shares one wardrobe:

  • The brother wants to store sneakers, the sister wants to store high heels
  • Dad's dress shoes and mom's slippers are mixed together
  • Over time, no one dares to delete anything (for fear of affecting others)

This is why your projects fight each other.


Chapter 2: Virtual environments - giving each project an independent room#

What professional developers do#

Don't let all projects share the system environment; instead, create an independent virtual environment for each project.

Virtual environment = independent room

Each project has its own room (the .venv folder):

  • Project A installs pandas 1.5 in its own room
  • Project B installs pandas 2.0 in its own room
  • The two rooms do not interfere with each other, each playing their own game

Understand with one image#

Core concept comparison

Directory structure perspective

Your computer

├─ System Python environment (public living room, keep it as empty as possible)
│  └─ Only install Python itself and the uv tool

└─ Your project folder

   ├─ Project A: Data Analysis
   │  ├─ analysis.py (your code)
   │  └─ .venv (Project A's independent room)
   │      └─ pandas 1.5

   └─ Project B: Web Scraper
      ├─ scraper.py
      └─ .venv (Project B's independent room)
          └─ pandas 2.0  ← Does not conflict with Project A!

Core values#

1. Version isolation

  • Project A uses pandas 1.5, Project B uses 2.0, and they do not affect each other

2. Clear dependencies

  • Each project's .venv only installs the libraries needed for that project
  • Three months later, when you rerun, the dependencies are clear at a glance

3. Reproducibility

  • Export requirements.txt, and others can recreate your environment with one click
  • No need to ask "What libraries did you install?"

4. Clean and deletable

  • Delete the project folder, and the .venv is deleted together
  • The system environment remains clean forever

Analogous understanding#

Without virtual environments:

The whole family shares one wardrobe (system environment)
├─ Dad's clothes
├─ Mom's clothes
├─ Brother's clothes
└─ Sister's clothes  ← All mixed together, no one dares to delete

With virtual environments:

Everyone has their own wardrobe (virtual environment)
├─ Dad's room/.venv  →  Stores dad's clothes
├─ Mom's room/.venv  →  Stores mom's clothes
├─ Brother's room/.venv  →  Stores brother's clothes
└─ Sister's room/.venv  →  Stores sister's clothes
                          ↑  No interference!

Chapter 3: Practical - Learn to manage virtual environments with uv in 5 minutes#

uv workflow overview

Now that you understand the concept of virtual environments, let's learn how to use them.

The traditional tools are pip + venv, but I recommend using uv directly: it's faster, simpler, and all-in-one.


Step 1: Install the uv tool (1 minute)#

Windows users:

Open PowerShell and run:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Mac/Linux users:

Open the terminal and run:

curl -LsSf https://astral.sh/uv/install.sh | sh

After installation, verify:

uv --version

If you see the version number, you succeeded!

uv version number


Step 2: Create your first virtual environment (2 minutes)#

Suppose you want to do a data analysis project.

2.1 Create a project folder

mkdir data-analysis
cd data-analysis

2.2 Create a virtual environment

Run in the project folder:

uv venv

You will see the prompt:

Creating virtual environment at .venv

This command creates a hidden .venv folder in the project folder, which contains:

  • An independent Python interpreter
  • An independent library storage space

venv folder


2.3 Activate the virtual environment

After creating it, you need to "activate" it to tell the computer, "Use this project's Python from now on."

Windows:

.venv\Scripts\activate

Mac/Linux:

source .venv/bin/activate

After successful activation, the terminal prompt will show (.venv):

(.venv) C:\Users\YourName\data-analysis>

This (.venv) indicates: You are now in the project's independent room!


Step 3: Install libraries and run code (2 minutes)#

Now you are in the virtual environment and can install libraries.

3.1 Install pandas

uv pip install pandas

uv is very fast, and it will be installed in a few seconds.

This pandas is only installed in .venv, and it won't affect the system environment!


3.2 Test code

Create a test.py file:

import pandas as pd

print(f"pandas version: {pd.__version__}")

data = pd.DataFrame({
    'Project': ['A', 'B', 'C'],
    'Dependency': ['pandas 1.5', 'pandas 2.0', 'openai 1.0']
})

print("\nThe virtual environment allows them to coexist peacefully:")
print(data)

Run:

python test.py

Output:

pandas version: 2.x.x

The virtual environment allows them to coexist peacefully:
  Project      Dependency
0      A  pandas 1.5
1      B  pandas 2.0
2      C  openai 1.0

Success!


3.3 Verify isolation (key experiment!)

Now let's do an experiment to verify that the virtual environment is indeed isolated.

Experiment 1: Exit the virtual environment

deactivate

The (.venv) disappears from the terminal, indicating you have returned to the system environment.


Experiment 2: Try to run the code

python test.py

Error:

ModuleNotFoundError: No module named 'pandas'

Why? Because pandas is only installed in .venv, and it's not in the system environment!


Experiment 3: Reactivate the virtual environment

# Windows
.venv\Scripts\activate

# Mac/Linux
source .venv/bin/activate

Run again:

python test.py

It runs normally again!

This is the magic of virtual environments:

  • Enter the room (activate) → have furniture (pandas)
  • Leave the room (deactivate) → empty (no pandas)
  • The system environment remains completely unchanged

Why choose uv instead of pip?#

Comparisonpip + venvuv
Installation speedSlow10-100 times faster
Installing pandas20 seconds2 seconds
Steps to operatepython -m venv .venv
activate
pip install
uv venv
activate
uv pip install
Learning curveNeed to learn two toolsOne tool does it all

For beginners, uv is simpler and faster.


Chapter 4: 3 common pitfalls for beginners#

I have taught over a dozen friends, and 90% of them fall into these 3 pitfalls.


Pitfall 1: Forgetting to activate the virtual environment before running code#

Symptoms:

Even though pandas is installed, it still throws ModuleNotFoundError.

Reason:

You installed it in the virtual environment but ran the code in the system environment.

Solution:

Develop the habit: Before running code, check if the terminal has (.venv).

If not, run:

# Windows
.venv\Scripts\activate

# Mac/Linux
source .venv/bin/activate

Once you see (.venv), run the code.


Activation status comparison:

Activation status comparison


Quick check command:

Not sure which environment you are in? Run:

python -c "import sys; print(sys.executable)"

If the output contains .venv, you're good:

C:\Users\YourName\data-analysis\.venv\Scripts\python.exe  ✅

If the output is the system path, you're wrong:

C:\Python\python.exe  ❌  Need to activate the virtual environment

Pitfall 2: Uploading the .venv folder to Git#

Symptoms:

The project folder is hundreds of MB, and uploading to GitHub takes forever.

Reason:

The .venv contains the complete code for all libraries, which is very large (100-500MB).

But it shouldn't be uploaded because:

  1. It's too large, wasting bandwidth
  2. Different operating systems are incompatible (Windows ones can't be used on Mac)
  3. Others can recreate it using requirements.txt

Solution:

Create a .gitignore file in the project root directory:

.venv/

Git will ignore .venv.


Correct approach:

Upload requirements.txt, not .venv.

Export the dependency list:

uv pip freeze > requirements.txt

When others get the code:

uv venv
source .venv/bin/activate
uv pip install -r requirements.txt

In a few seconds, the environment will be identical!


Pitfall 3: Not knowing the purpose of requirements.txt#

Scenario:

Three months later, you want to rerun the project but forgot which libraries you installed.

Or, you send the code to a friend, and they don't know what to install.

Solution:

Use requirements.txt to record dependencies.

Generate:

uv pip freeze > requirements.txt

File content (records exact versions):

pandas==2.1.0
numpy==1.25.2
requests==2.31.0

Use:

uv pip install -r requirements.txt

Install all dependencies with one command, ensuring version consistency.


Analogy:

Collaboration flowchart

requirements.txt = shopping list
You go to the supermarket (PyPI) to buy things (install libraries) according to the list

Best practice:

Each time you install a new library, update requirements.txt:

uv pip install new-package
uv pip freeze > requirements.txt
git add requirements.txt
git commit -m "add new-package"

Chapter 5: A checklist to establish good habits#

Standard process for new projects (6 steps)#

□ Create project folder: mkdir my-project
□ Enter folder: cd my-project
□ Create virtual environment: uv venv
□ Activate environment: source .venv/bin/activate (Mac) or .venv\Scripts\activate (Win)
□ Install dependencies: uv pip install pandas numpy
□ Export dependencies: uv pip freeze > requirements.txt
□ Create .gitignore: echo ".venv/" > .gitignore

Post this checklist on your desk to develop muscle memory.


Common command quick reference#

OperationWindowsMac/Linux
Create virtual environmentuv venvuv venv
Activate.venv\Scripts\activatesource .venv/bin/activate
Exitdeactivatedeactivate
Install libraryuv pip install library-nameuv pip install library-name
Export dependenciesuv pip freeze > requirements.txtSame as left
Install dependenciesuv pip install -r requirements.txtSame as left

Troubleshooting checklist#

Code fails to run? Check in order:

□ Is the virtual environment activated? (Does the terminal have the (.venv) mark?)
□ Are the libraries installed in the virtual environment? (Check with pip list after activation)
□ Is the terminal's current directory correct? (Check with pwd or cd)
□ Is requirements.txt updated?

3 iron rules#

Iron rule 1: Never install libraries in the system environment
The system environment should only have Python and uv; nothing else should be installed.

Iron rule 2: The first thing for a new project - create a virtual environment
Develop the habit: mkdir → cd → uv venv → activate

Iron rule 3: Use uv consistently, do not mix with pip
Do not mix pip install and uv pip install.


What to learn next?#

You have now mastered the core skills of virtual environments!

Optional advanced directions:

  1. Learn Git version control (manage code changes)
  2. Learn VS Code + Python plugin (professional editor)
  3. Learn Jupyter Notebook (interactive programming)
  4. Deep dive into uv advanced features (uv.lock lock file)

Most important advice:

Don't just read tutorials; get hands-on with 3 projects:

  1. Project 1: Data analysis script (using pandas)
  2. Project 2: Simple web scraper (using requests)
  3. Project 3: AI chatbot (using openai)

Use a virtual environment for each project, and after completing all three, your understanding of virtual environments will be deeper than reading the tutorial 10 times.


Remember this phrase:

"Virtual environments are not a hassle, but a lifesaver."

Now you know how to avoid projects fighting each other; go use AI to do something interesting!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.