(Snippets taken from the Python Manual)
To create a virtual environment, decide upon a directory where you want to place it, and run the venv
module as a script with the directory path:
python3 -m venv tutorial-env
This will create the tutorial-env
directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files.
Once you’ve created a virtual environment, you may activate it. On Unix or MacOS, run:
source tutorial-env/bin/activate
(This script is written for the bash shell. If you use the csh or fish shells, there are alternateactivate.csh
and activate.fish
scripts you should use instead.)
Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using, and modify the environment so that running python
will get you that particular version and installation of Python.
Managing Packages with PIP
From within the virtual environment:
(tutorial-env) $ python -m pip install novas
(tutorial-env) $ python -m pip install requests==2.6.0
(tutorial-env) $ python -m pip install --upgrade requests
pip uninstall
followed by one or more package names will remove the packages from the virtual environment.pip show
will display information about a particular packagepip list
will display all of the packages installed in the virtual environmentpip freeze
will produce a similar list of the installed packages, but the output uses the format that pip install
expects
(tutorial-env) $ pip freeze > requirements.txt (tutorial-env) $ cat requirements.txt
(tutorial-env) $ python -m pip install -r requirements.txt
To run a script without pre-loading the virtual environment
tutorial-env/bin/python script.py
Or, using the activate script:
tutorial-bin/bin/activate
python script.py