How to Set Up Python Virtual Environments?

Estimated read time 2 min read

Setting up Python virtual environments can help you keep your project dependencies separate from other projects on your system. Here are the steps to set up a Python virtual environment:

  1. Open a terminal or command prompt window.
  2. Make sure you have the venv module installed by typing python3 -m venv --help. If the module is not installed, you can install it with sudo apt-get install python3-venv on Ubuntu/Debian or pip install virtualenv on other platforms.
  3. Navigate to the directory where you want to create your virtual environment.
  4. Create a new virtual environment by typing python3 -m venv myenv (replace myenv with the name you want to give your virtual environment).
  5. Activate the virtual environment by typing source myenv/bin/activate on Linux/macOS or myenv\Scripts\activate on Windows.
  6. Once activated, you will see the name of your virtual environment in your terminal prompt.
  7. Install packages and dependencies for your project using pip as you normally would. The packages will be installed only in your virtual environment and not in the system’s Python installation.
  8. When you’re done working on your project, you can deactivate the virtual environment by typing deactivate.

Here’s an example of how to create a virtual environment and install the numpy package:

$ cd myproject
$ python3 -m venv myenv
$ source myenv/bin/activate
(myenv) $ pip install numpy

Now you can work on your project with the numpy package installed in your virtual environment. When you’re done, you can deactivate the virtual environment with deactivate:

(myenv) $ deactivate

Note that each time you want to work on your project, you need to activate the virtual environment first.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply