How To Run Python IDLE Within The Context Of A Pipenv Virtual Environment

Since writing this guide, I've defaulted to using venv in Python 3 for my virtual environment needs. For quick scripts, you can also just use the excellent browser and cloud-based REPL.it.


If you've never heard of Pipenv, it's a neat little utility that helps you create a virtual environment for your Python project and then you can install all the dependencies in there and it would not pollute your base python environment. This way you can maintain different versions of the library.

For quick scripts, I like to use the default Python IDLE program that comes with Python on Windows because it really helps you create something quickly using the REPL environment which I haven't been able to figure out in VS Code.

The problem is, how I use the Python IDLE program within a Pipenv context rather than the default python context?

So let's get into it, the first thing you want to do is open up a command prompt window (Ctrl+R to open run and then type 'cmd'). Let's say you want to make a project so you'll make a new directory for it (we'll use C:\tmp) in which you will have your Python project and then you'll execute pipenv install pandas. It's going to take a while for it to create the virtual environment and install the pandas library on it.

Open up notepad and create a notepad file where we're going to be typing some code that will open the IDLE program. This code is only compatible with Python 3.6+.

Paste in the following snippet.

from idlelib.pyshell import main

if __name__ == '__main__':
    main()

We will run this piece of code in the virtual environment we just created, which will open up an IDLE window within the context of the current directory where the pandas library is already installed.

Start pipenv shell which opens up the shell environment for Pipenv within the virtual environment in which all of your libraries are installed where we can run Python as usual. Now execute python main.py and a new IDLE window will open up.

In this REPL, type import pandas as pd, if there are no errors it means you're good to go.

So now what I want to do is to document the code in a new file that I will run every time.

Open up another IDLE window from within IDLE and save that as another file. Type in name = Shuaib' in that file and then hit F5 (Run the file).

Now if you type name in the REPL, you'll see the variable was available.

That's how easy it is to run IDLE in a Pipenv created virtual environment and keep your global base python namespace clean!