How to associate a Python 3 virtual environment with Thonny
When you are developing a Python 3 application with Thonny, you may want to get Thonny to use a virtual environment to run and debug your application.
With this in mind, this post shows you how to associate a Python 3 virtual environment with Thonny.
Creating a virtual environment with python3-venv
This tutorial was created with Thonny running on Raspbian Stretch. The steps to associate a Python 3 virtual environment with Thonny running on Windows should be similar.
Before proceeding further, make sure that you had created a virtual environment. In case you need it, you can follow one of the following tutorials to create your Python 3 virtual environment:
- Create a virtual environment with python3-venv on Linux or Unix.
- Create a Python 3 virtual environment on Windows 10
For the purpose of this post, let's assume that we had created a Python 3 virtual environment at /home/pi/my-venv.
Steps to associate a Python 3 virtual environment with Thonny
Firstly, open up your Thonny IDE.
If you see that your Thonny IDE does not have the menu bar, click on Switch to regular mode on the top right corner. After you had done so, Thonny will show you a confirmation message:
Click on Ok and reopen Thonny. After Thonny had been reopened, it will show a menu bar at the top:
Given that, go to Tools -> Options:
Click on the Interpreter tab:
As shown above, Thonny is using the same Python interpreter which runs Thonny to run your Python 3 application. Click on the combo box and choose Alternative Python 3 interpreter or virtual environment:
Click on Locate another python executable... and a file dialog will appear for you to choose the python executable inside your virtual environment:
Click Ok to confirm your selection:
Click Ok again to confirm your configuration changes. Once you had done so, you will see that Thonny restarts the shell below with the Python executable from your virtual environment:
Given that, Thonny will run your Python 3 application inside your virtual environment.