Summary of what I have learned (success)
Virtual Python Environments With Specific Python Versions
Using:
python3 -m venv
pyenv
Virtual environments are part of the Python3 package (since v3.3)
- To create a virtual environment for a project:
$ cd my_project_folder
- using the default python3 version and no installed site packages
$ python3 -m venv dir_name (common to use venv for dir_name) or
- or to use default python3 version and the installed site packages
$ python3 -m venv --site-packages venv-w-site-packages
$ cd my_project_folder
$ source venv/bin/activate
or
$ source venv-w-site-packages/bin/activate
(venv) $
or
(venv-w-site-packages) $
To save the current state of the environment:
(venv) $ pip freeze > requirements.txt
To recreate installed packages in a new venv:
(venv) $ pip install -r requirements.txt
To stop using the virtual env:
(venv) $ deactivate
!!! Be sure to add the virtual environment folder to the .gitignore list if not named venv
pyenv - To run a Python version different than the installed “system python”
see https://yeti.co/blog/setting-up-a-raspberry-pi-with-raspbian-and-pyenv-running-python-35/
and see: https://github.com/pyenv/pyenv
- Setup Dependencies: WARNING Updating Your System Might Break Stuff !!! WARNING
sudo apt-get update && sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev openssl bzip2
- Run pyenv-installer:
cd ~
curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash
- Copy lines into ~/.bashrc (or any file executed by ~/.bashrc)
export PATH="~/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
- Run the .bashrc:
source ~/.bashrc or . ~/.bashrc
- To create a Python version for use in your environments
cd ~
pyenv install --list to see what versions available
pyenv install 3.7.6
and in 15 minutes (Pi3) you should have the python available in ~/.pyenv/bin
-
Familiarize with all pyenv commands:
https://github.com/pyenv/pyenv/blob/master/COMMANDS.md
-
See what python version are available and what is current
$ pyenv versions - to shall all versions and * by current
or
$ pyenv version - to show current version
- Designate a project local python version
cd <Project>
pyenv local 3.7.6
- create a virtual environment that uses that version of python
cd \<Project\>
python -m venv [--site-packages] venv
- Test it worked
$ source ~/.bashrc
$ source venv/bin/activate
(venv) $ python --version
(venv) $ deactivate
$ pyenv which python3 - displays path to python in use
To designate a project should use the system version:
$ pyenv local --unset
To run a virtual env from the root crontab:
* * * * * /usr/bin/env bash -c 'YOUR_COMMAND_HERE' > /dev/null 2>&1
e.g.:
@reboot /usr/bin/env bash -c 'cd /home/user/project && source /home/user/project/env/bin/activate && ./myprogram.py arg' > /dev/null 2>&1