# How to set up Python virtual environments in Replit

- Tool: Replit
- Difficulty: Intermediate
- Time required: 20 minutes
- Compatibility: All Replit plans. Python 3.10+ via default Nix module. Poetry and pip available in Shell.
- Last updated: March 2026

## TL;DR

Replit automatically creates a Python virtual environment for every Python project, but you may need to manage it manually when dealing with specific package versions, poetry-based projects, or Nix-level Python version changes. Use pip for simple installs, poetry for dependency locking, and the replit.nix file to switch Python versions at the system level.

## Manage Python environments and dependencies in Replit

Replit handles Python virtual environments differently from a local development setup. Every Python Repl automatically creates a venv in a hidden directory, and pip installs go into that environment by default. However, things get more complex when you need a specific Python version, locked dependencies with poetry, or system-level packages via Nix. This tutorial covers all three layers of Python environment management in Replit so you can avoid the ModuleNotFoundError and version mismatch issues that commonly frustrate Python developers on the platform.

## Before you start

- A Replit account with a Python project (any plan)
- Basic familiarity with Python imports and pip install
- Access to the Shell pane (Tools dock > Shell)
- Understanding of why virtual environments exist (dependency isolation)
- Knowledge of how to show hidden files in Replit (filetree menu > Show hidden files)

## Step-by-step guide

### 1. Understand Replit's automatic virtual environment

When you create a Python Repl, Replit automatically sets up a virtual environment in a hidden directory. This venv is activated by default whenever you use the Shell or Run button, so pip install commands install packages into the project's isolated environment rather than the system Python. You can verify this by running which python in the Shell, which should point to a path inside your project rather than /usr/bin/python. This automatic setup means you do not need to run python -m venv or activate scripts like you would locally.

```
# Run these in the Shell to inspect your environment
which python
python --version
pip list
```

**Expected result:** The Shell shows that python points to the project's virtual environment, not the system Python. pip list shows only packages installed in this project.

### 2. Install packages with pip

The simplest way to add Python packages in Replit is pip install in the Shell. Replit also auto-installs packages when it detects import statements in your code, but this automatic installation can be unreliable for packages with complex names or optional dependencies. Always verify installation by importing the package in the Shell. For reproducibility, create a requirements.txt file so your dependencies are documented and can be reinstalled if the environment resets.

```
# Install a single package
pip install requests

# Install from a requirements file
pip install -r requirements.txt

# Create a requirements file from current environment
pip freeze > requirements.txt

# Install a specific version
pip install flask==3.0.0
```

**Expected result:** Packages install into the project's virtual environment. Running pip list shows the newly installed packages.

### 3. Use poetry for dependency management

Poetry is a more robust dependency manager that creates a poetry.lock file for deterministic installs. Replit supports poetry natively. If your project already has a pyproject.toml file, poetry is likely already configured. Poetry resolves dependency conflicts automatically and separates development dependencies from production ones. Use poetry add to install packages and poetry install to restore the environment from the lock file.

```
# Install poetry if not already available
pip install poetry

# Initialize a new poetry project
poetry init --no-interaction

# Add a package
poetry add requests

# Add a dev-only package
poetry add --group dev pytest

# Install all dependencies from lock file
poetry install

# Run a script through poetry's environment
poetry run python main.py
```

**Expected result:** Poetry creates pyproject.toml and poetry.lock files. Packages are installed and available for import.

### 4. Change the Python version via Nix

Replit uses Nix for system-level configuration, including the Python version. To switch Python versions, you need to modify the replit.nix file (show hidden files first). Change the Python package reference to the version you need. After saving, run exit in the Shell to reload the Nix environment. Available Python packages include pkgs.python310, pkgs.python311, and pkgs.python312. Note that changing the Python version may require reinstalling your pip packages.

```
# replit.nix — change the Python version here
{ pkgs }: {
  deps = [
    pkgs.python311
    pkgs.python311Packages.pip
  ];
}
```

**Expected result:** Running python --version in a new Shell session shows the updated Python version. You may need to reinstall packages with pip install -r requirements.txt.

### 5. Handle system-level dependencies with Nix

Some Python packages require system-level libraries that are not included in Replit's default environment. For example, Pillow needs image processing libraries, and psycopg2 needs PostgreSQL client libraries. Add these system dependencies to replit.nix alongside your Python packages. Search for available packages at search.nixos.org/packages. This is the most common cause of 'failed building wheel' errors during pip install.

```
# replit.nix with system dependencies for common packages
{ pkgs }: {
  deps = [
    pkgs.python311
    pkgs.python311Packages.pip
    pkgs.zlib
    pkgs.libjpeg
    pkgs.libpng
    pkgs.postgresql
  ];
}
```

**Expected result:** After reloading the Shell with exit, pip install commands for packages like Pillow and psycopg2 succeed without 'failed building wheel' errors.

### 6. Troubleshoot common environment errors

The most frequent Python environment errors in Replit are ModuleNotFoundError (package not installed or wrong environment), version conflicts between packages, and 'failed building wheel' (missing system dependencies). When you encounter these, first verify your environment with which python and pip list. If packages seem to disappear, the virtual environment may have been corrupted. The nuclear option is deleting the .pythonlibs directory and reinstalling everything from requirements.txt.

```
# Diagnostic commands for environment issues
which python
python --version
pip list
pip check  # verify no broken dependencies

# Nuclear reset: delete and recreate the environment
rm -rf .pythonlibs
pip install -r requirements.txt
```

**Expected result:** After running diagnostics, you can identify whether the issue is a missing package, wrong Python version, or corrupted environment, and apply the appropriate fix.

## Complete code example

File: `setup_environment.sh`

```bash
#!/bin/bash
# Python environment setup script for Replit
# Run this in the Shell after creating a new Python project

echo "=== Python Environment Setup ==="
echo ""

# Check current Python version
echo "Python version:"
python --version
echo ""

# Check pip
echo "pip version:"
pip --version
echo ""

# Check virtual environment
echo "Python path:"
which python
echo ""

# Install from requirements if the file exists
if [ -f "requirements.txt" ]; then
    echo "Installing from requirements.txt..."
    pip install -r requirements.txt
else
    echo "No requirements.txt found. Creating one..."
    echo "# Add your project dependencies here" > requirements.txt
    echo "# Example:" >> requirements.txt
    echo "# requests==2.31.0" >> requirements.txt
    echo "# flask==3.0.0" >> requirements.txt
    echo "Created requirements.txt template."
fi

echo ""

# Verify no broken dependencies
echo "Checking for dependency conflicts..."
pip check

echo ""
echo "=== Environment Ready ==="
echo "Installed packages:"
pip list --format=columns
```

## Common mistakes

- **Running python -m venv to create a manual virtual environment, which conflicts with Replit's built-in venv** — undefined Fix: Do not create your own venv. Replit automatically manages a virtual environment for every Python project. Use pip install directly.
- **Editing replit.nix but not reloading the Shell, so the old Python version stays active** — undefined Fix: After changing replit.nix, type exit in the Shell to close it, then open a new Shell session. Verify with python --version.
- **Not adding workspace secrets to the deployment configuration, causing os.getenv() to return None in production** — undefined Fix: Secrets must be added separately in the Deployments pane. Workspace secrets do not automatically carry over to deployments.
- **Installing packages globally with sudo pip install, which does not work in Replit's sandboxed environment** — undefined Fix: Use pip install without sudo. Replit's environment does not support sudo. Packages install into the project's virtual environment by default.
- **Deleting the .pythonlibs directory without having a requirements.txt, losing all installed packages** — undefined Fix: Run pip freeze > requirements.txt before deleting .pythonlibs. Then reinstall with pip install -r requirements.txt.

## Best practices

- Always maintain a requirements.txt or pyproject.toml file so your environment can be reproduced from scratch
- Use pip freeze > requirements.txt after installing new packages to keep the file up to date
- Pin package versions in requirements.txt (e.g., requests==2.31.0) to avoid unexpected breaking changes
- Add system-level dependencies to replit.nix rather than trying to install them with pip
- Run exit in the Shell after modifying replit.nix to reload the Nix environment
- Use poetry for projects with complex dependency trees that need deterministic resolution
- Check the Resources panel if pip install hangs — large packages can consume significant RAM on the free tier
- Keep your requirements.txt clean by separating development dependencies (pytest, pylint) from production ones

## Frequently asked questions

### Does Replit automatically create a virtual environment for Python projects?

Yes. Every Python Repl has an automatic virtual environment. Packages installed with pip go into a hidden .pythonlibs directory. You do not need to create or activate a venv manually.

### How do I change the Python version in Replit?

Edit the replit.nix file (enable Show hidden files first) and change the Python package to the version you need (e.g., pkgs.python311 or pkgs.python312). Then type exit in the Shell and open a new session.

### Why does pip install fail with 'failed building wheel' errors?

The package requires system-level libraries not included in Replit's default environment. Add the needed dependencies to replit.nix. For example, Pillow needs pkgs.zlib and pkgs.libjpeg. Search for packages at search.nixos.org/packages.

### Should I use pip or poetry in Replit?

Use pip for simple projects with a few dependencies. Use poetry for larger projects that need deterministic dependency resolution, lock files, and separation of dev and production dependencies.

### Why do my installed packages disappear after restarting the Repl?

This can happen if the virtual environment was corrupted or if a Nix environment change reset the Python installation. Always maintain a requirements.txt file and run pip install -r requirements.txt after any environment reset.

### Can RapidDev help with complex Python environment issues on Replit?

Yes. RapidDev's engineering team can help resolve tricky dependency conflicts, Nix configuration issues, and deployment environment mismatches that go beyond basic pip install troubleshooting.

### How do I install a package from a private Git repository in Replit?

Store a personal access token in Tools > Secrets as GIT_TOKEN. Then install with pip install git+https://${GIT_TOKEN}@github.com/user/repo.git in the Shell.

### What is the difference between replit.nix and requirements.txt?

replit.nix manages system-level packages (Python itself, C libraries, system tools). requirements.txt manages Python-level packages (Flask, requests, etc.). Both are needed for a fully configured environment.

---

Source: https://www.rapidevelopers.com/replit-tutorial/how-to-set-up-a-virtual-environment-for-python-projects-within-replit
© RapidDev — https://www.rapidevelopers.com/replit-tutorial/how-to-set-up-a-virtual-environment-for-python-projects-within-replit
