I thought I would write a brief blog to capture the notes I use when I create a new Python 3 project. I’m working on MacOS but the process should be the same on other Unix/Linux based systems and the principles should be the same if you are working on Windows.
Step 1: Create a new directory to house your project
Step 2: Create a Python virtual environment so we can create a local set of dependancies for this project.
python3 -m venv venv
Step 3: Activate your virtual environment
After doing this you can confirm at anytime which Python environment you are using with the following command
Just have a look at the directory path that is returned and confirm it is a sub-directory of the directory you created in step 1 above.
Step 4: If you have a ‘requirements.txt’ listing the dependancies for the new project run it now.
pip install -r requirements.txt
check the list afterwards using pip list
If you don’t have a requirements.txt and you want to package up an existing project to install into this new environment, please see below – how to package a python project.
Step 5: Create some new Python source
Don’t put your own source in the venv directory, keep it in the parent directory. For example
The code command is the command line shortcut to launch Microsoft Visual Studio Code.
Step 6: If you are using VS Code, it doesn’t seem to detect the virtual environment automatically all the time. So you need to manually tell it which environment to use for your code.
In Code do CMD-SHIFT-P then search for Python: Select Interpreter. Look down the list and select the Python executable in the venv directory we created in step 2.
Step 7: Set-up GIT version control and omit the venv directory in your .getignore file.
Then create a file called .gitignore in the projects root directory and add all the files and directories that you don’t want version tracked, for example:
venv/ .vscode/ archive/ *.csv
How to package a Python project
If you want to be able to package your Python project so that you can transfer it to another machine / server you first need to understand the dependancies your project has. This in simple terms means the various packages you’ve installed with pip.
To do this you can use the pip freeze
pip freeze > requirements.txt
This creates a simple text file listing all the packages which are part of your project and their versions. This can then be fed into the pip install process.
- If you want to leave your VENV virtual environment at any time, you can either switch to another environment using the activate step shown above or you can exit completely back to your systems default Python using the deactivate command.
- If you don’t have the VENV command installed in your Python environment use the command pip3 install virtualenv to install it.
- There is a good example of a complete / best practice Python .getignore file here https://github.com/github/gitignore/blob/master/Python.gitignore