I’ve been changing my thoughts on using Python Virtual environments. I last talked about the topic in December of 2018. Twice actually.
I’m not working the way I was when I wrote those posts, mostly because I’ve learned to do new things along the way.
My current layout, which works pretty well for me, is to create a “projects” folder and then the venv folder under it. I also try to have a folder outside of the projects called .skel. It is a throwback to the /etc/skel folder in Linux.
1 2 3 4 5 6 7 8 9 10 |
~/projects$ ls -a1 . .. AtBS_Udemy http_extractor python_basics python_tricks .skel test ua_selector |
My .skel directory contains typical files that Github creates in a new repo. The .gitignore file for Python, the License file, and the README.md file. I also have a blank template for setup.py. The template allows me to enter the data needed. I based it on the setup.py file from the Real Python “Python Package tutorial.”
1 2 3 4 5 6 |
~/projects$ tree .skel/ .skel/ ├── LICENSE.txt ├── README.md ├── requirements.txt └── setup.py |
Here is what tree displays in a new project folder called ua_selector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
~/projects$ tree -L 2 ua_selector/ ua_selector/ ├── LICENSE.txt ├── README.md ├── requirements.txt ├── setup.py ├── ua_selector │ ├── __init__.py │ ├── __main__.py │ └── user_agents.cfg └── venv ├── bin ├── include ├── lib ├── lib64 -> lib ├── pyvenv.cfg └── share |
I usually try to keep one folder under projects called test. That folder is where I test my current code projects. Using python -m pip install -e ../<project folder>/ works great so far. Of course, I run the python command inside the virtual environment.
1 2 3 |
~/projects$ tree -L 1 test test └── venv |
To activate the environment, I use the command ae, and to deactivate, I use de. I forgot who I got these from, but I like using them, it was in a youtube video, but I can’t find it now. Add these to either your .bashrc, .bash_alias file, or whatever your shell’s configuration file is that has alias options.
1 2 3 |
# python venv aliases alias ae='deactivate &> /dev/null; source ./venv/bin/activate' alias de='deactivate' |
ae It tries to deactivate any venv you may be in after changing files and then activates the venv in that directory. de just deactivates the environment.
Before I realized the power of python -m pip install -e the other day, I had a quick shell one-liner doing
1 |
de ; cd - ; ae |
to change back and forth from the directory I was writing code in, and the one I was testing it in. I was working through problems having the code be an installable package. Yes, the de was a redundant action above; it was a lousy coding session, and I wasn’t trusting anything I wasn’t running by hand at that point.
Oh, and that ua_selector project, more on that later.