Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

programming python venv

venv basics

What is a venv

Virtual environments allow you to have different versions of modules installed at the same time on the same system.

Why venv are Useful

Sometimes, dependencies of modules require specific versions of a module, but that limits other scripts to that version if they are in the same environment. By using venv you can specify multiple environments and use any version combination you want. This helps keep your system stable, and ensures that your scripts reliably run.

Requirements Files

Pip is the module installer for python, and it should be updated before installs. It helps work out dependencies for you. A requirements file is a list of modules that a script needs to run, and allows you to setup a new environment, and then install the modules that environment/script needs. It allows you to reliably install the script in multiple environments.

python -m venv example
cd example
scripts\activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt

On Linux, you would use:

python3 -m venv example
cd example
source bin\activate
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt

Windows

Example

Here is full example for a game I am working on called “9 mens morris”. It’s like advanced tic tac toe, except much better. It’s not my game, but the code is mine, written before chatgpt!

git clone https://github.com/rubysash/9menmorris.git
python -m venv 9menmorris
cd 9menmorris
scripts\activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python NineMenMain.py 

venv Shortcut on Windows

python -m venv mm

Create a mm.bat file in the mm directory above. Then copy and paste shortcut to that .bat file wherever you want (like on your desktop).

start cmd /k "Scripts\activate && python mm.v12.py"

Linux

venv Shortcut on Linux

I create all of my virtual environments in a folder called “v” in my /home/james/ folder:

cd ~/v
python3 -m venv mm

Save this text file as mm.desktop in your /home/james/Desktop folder

[Desktop Entry]
Version=1.0
Type=Application
Name=Mark Down Maker
Comment=
Exec=sh -c '/home/james/v/mm/bin/python3 /home/james/v/mm/mm.v12.py'
Icon=account-edit
Path=/home/james/v/mm
Terminal=false
StartupNotify=false

For the shortcut to open when you click it, these files must be chmod +x:

  • /home/james/v/mm/bin/python3
  • /home/james/v/mm/mm.v12.py
  • /home/james/Desktop/mm.desktop

Linux venv Example

If you happen to want to try my game, it’s pretty fun.

git clone https://github.com/rubysash/9menmorris.git
python3 -m venv 9menmorris
cd 9menmorris
source bin\activate
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt
python3 NineMenMain.py 

Last updated on 4 Feb 2024
Published on 4 Feb 2024