DEV Community

Omkar Bhagat
Omkar Bhagat

Posted on

Guide To Installing Python Packages In Virtual Environment

Never install packages "globally." If Project A needs Django 3 and Project B needs Django 5, your system will crash. Use a virtual environment (venv) to keep them isolated.

python3 -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Activate it:

source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

pip is your package downloader. Once your environment is active, use it to grab libraries from the web.

  • Install a package: pip install requests

  • Install a specific version: pip install fastapi==0.110.0

  • Remove a package: pip uninstall requests

Don't make people guess what they need to run your code. Create a requirements file.

To save your current setup:

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

To install everything from someone elseโ€™s list:

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Sample requirements.txt file:

# Web Framework
fastapi==0.109.0
uvicorn==0.27.0

# Database
sqlalchemy==2.0.25
psycopg2-binary==2.9.9

# Utilities
requests==2.31.0
python-dotenv==1.0.0
Enter fullscreen mode Exit fullscreen mode

To stop using your current virtual environment and return to your system's global Python, simply type:

deactivate
Enter fullscreen mode Exit fullscreen mode

Top comments (0)