How to Set Up a Python Virtual Environment (venv)?

Estimated read time 2 min read

To set up a Python virtual environment using the built-in venv module in Python, you can follow these steps:

  1. Open your command prompt or terminal.
  2. Navigate to the directory where you want to create your virtual environment.
  3. Create a new virtual environment by running the following command: python -m venv myenv (replace “myenv” with the name you want to give to your virtual environment).
  4. Activate the virtual environment by running the following command:
    • For Windows: myenv\Scripts\activate.bat
    • For Linux/Mac: source myenv/bin/activate
  5. You should now see the name of your virtual environment in the command prompt or terminal, indicating that you are now working inside the virtual environment.
  6. You can now install any Python packages or libraries that you need for your project using pip, and they will be installed only in the virtual environment, keeping your system’s Python installation clean.
  7. To deactivate the virtual environment, simply type deactivate in the command prompt or terminal.

Here is an example of how you might set up a virtual environment and install some packages:

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

In this example, we are creating a new virtual environment called myenv, activating it, and then installing the numpy and pandas packages using pip. When we are done working in the virtual environment, we simply type deactivate to exit the virtual environment.

Note that this is just a basic example to get you started. You can use virtual environments to isolate Python dependencies for any project, regardless of its size or complexity.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply