How to Set Up a Python Virtual Environment in Visual Studio Code?

Estimated read time 2 min read

You can set up a Python virtual environment in Visual Studio Code using the following steps:

  1. Open your project folder in Visual Studio Code.
  2. Open the integrated terminal in Visual Studio Code by going to View > Terminal or by pressing the shortcut Ctrl + Shift + ~ (Windows/Linux) or Cmd + Shift + ~ (Mac).
  3. In the terminal, navigate to the root folder of your project.
  4. Create a new virtual environment by running the following command: python -m venv env (replace “env” with the name you want to give to your virtual environment).
  5. Activate the virtual environment by running the following command: .\env\Scripts\activate (Windows) or source env/bin/activate (Mac/Linux).
  6. You should now see the name of your virtual environment in the terminal, indicating that you are now working inside the virtual environment.
  7. Install any required Python packages or libraries using pip. For example, you can install the Flask framework by running the following command: pip install flask.
  8. You can now run your Python code within the activated virtual environment.

Note that Visual Studio Code also provides an option to create and manage virtual environments directly from the editor. You can go to the Command Palette by pressing the shortcut Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac) and search for the command Python: Create a New Environment. This will open a prompt where you can choose the location and name of the virtual environment and specify the Python interpreter to use. You can also use the Python: Select Interpreter command to select an existing virtual environment as your interpreter.

Once you have created or selected a virtual environment, you can activate it in the integrated terminal by running the command .\<env-name>\Scripts\activate (Windows) or source <env-name>/bin/activate (Mac/Linux).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply