DEV Community

Soukaina Tyes
Soukaina Tyes

Posted on

How to Create a Python virtual environment

install virtualenv

  • First, it's better to check if virtualenv is already installed. this can be done by running the following command:
virtualenv --help
Enter fullscreen mode Exit fullscreen mode
  • If you encounter an error message like "command not found," it indicates that virtualenv is not installed and you need to install it. Otherwise, the usage and options are displayed.

  • To install it, use the command:

pip install virtualenv
Enter fullscreen mode Exit fullscreen mode

Create a Virtual Environment:

  • To create a new virtual environment, simply execute:
virtualenv name_of_virtual_envirement
Enter fullscreen mode Exit fullscreen mode

A directory of the name will be then created:

Activate the virtual environment

  • to activate the virtual environment, navigate to the directory and execute the following:
source bin/activate
Enter fullscreen mode Exit fullscreen mode

To deactivate it

  • To exit the virtual environment, simply run:
deactivate
Enter fullscreen mode Exit fullscreen mode

How does it work

  • Once you're in the Python virtual environment any Python packages you install using pip are local to the environment, i.e.: They won't affect your global Python installation.
  • To view the packages installed in your virtual environment, you can:

  • First, install a package, for example:

pip install discord
Enter fullscreen mode Exit fullscreen mode
  • then:
pip freeze
Enter fullscreen mode Exit fullscreen mode
  • the name of the package, its dependencies, and respective versions should appear
  • you can also save your environment packages in a requirement.txt file using the following command:
pip freeze > requirement.txt
Enter fullscreen mode Exit fullscreen mode
  • Later, if you want to install all the dependencies of your project in a single step, you can use:
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Top comments (0)