Skip to main content

Section C.2 Python Virtual Environment

There is a very good chance your system has a version of Python installed already since various other programs rely on it. You will be much happier if various Python programs you need for PreTeXt do not get entangled with your Python programs installed as system software. And if we need to help you debug some related problems we will ask you to work in a virtual environment anyway. We will follow a primer 1  that has been recommended by Brad Miller, founder of Runestone Interactive. See that page for more details.

realpython.com/python-virtual-environments-a-primer/

These are condensed instructions without much explanation.

  1. Do not install the old-school virtualenv module.

  2. Make a directory anywhere you like named virtual-python and change into it.

  3. python3 -m venv ptx makes a virtual environment named ptx. (Requires Python 3.6 or later.)

Done. But how do you use it?

  1. To activate your virtual environment, be sure you are in the virtual-python directory. For Mac or Linux, with a bash shell go

    source ptx/bin/activate
    (ptx) $
    

    There are other scripts for other shells, take a look around.

    For Windows, go

    ptx/Scripts/activate.bat
    (ptx) >
    

    Notice that your prompt has changed to remind you that now anything you do with Python will be “sandboxed” in this virtual environment and not get mixed up with your system Python.

  2. Now you can do any Python-related task using your virtual environment, and can change directories if desired.

  3. When you are finished with your virtual environment, on Mac or Linux with a bash shell you simply go

    (ptx) $ deactivate
    $
    

    For Windows, similarly

    (ptx) > deactivate
    >
    

    We have one report, on a Mac, of deactivation dropping you into a different virtual environment named (base). A way to leave that virtual enviroment is to run

    (base) $ conda deactivate
    

    This appears to be due to Anaconda somehow creating a default base environment initially. If you have this experience and find a simple solution, please report it. Some details at Stack Overflow 54429210 2  may be helpful.

stackoverflow.com/questions/54429210