Gangmax Blog

Make Python Packages Work in Visual Studio Code

Here are the steps how I made an existing Python project working in VSC, especially how the Python packages work. From here.

First, open the Python project in VSC. At this moment you will notice that all the Python code lines where any external Python package is used are red, which means VSC cannot find their definitions.

  1. Select a Python interpreter

    Open the Command Palette (⇧⌘P), type “Python: Select Interpreter” and set the value “~/.pyenv/versions/3.8.5” in it. Note that I’m using “pyenv” on my Mac and the Python version I’m using is “3.8.5”. At the first time I set the value as “~/.pyenv/shims/python” but it didn’t work. You need to update the value as yours.

  2. Create a virtual environment in VSC

To create a virtual environment in VSC, press “(⌃⇧`)” to open a terminal inside VSC. In the opened terminal, run the following commands:

1
2
python -m venv .venv
source .venv/bin/activate

Note that, when you do so, you’ll be prompted by VSC that “We noticed a new virtual environment has been created. Do you want to select it for the workspace folder?”. Choose “Yes”. And also, a “.venv” directory now is created in your project directory, you may want to add it in your “.gitignore” file to prevent from adding it to your Git repository.

Now the virtual environment is created, you can install the Python pip package inside the VSC terminal window as your want like below:

1
2
pip install requests
...

Now if everything works, VSC can recognize the Python code lines which use external Python packages. And everytime you press “(⌃⇧`)”, the virtual environment will be automatically activated when the new terminal is opened.

Comments