Development/Python: Difference between revisions
(→Virtual Environments and Package Management: UV ersetzt Pixi nicht, weil Pixi auch Conda Pakete installieren kann. Daher habe ich das aus dem Beschreibungstext rausgenommen. Außerdem gibts bei pipx soweit ich weiß keine Möglichkeit was bei PyPI zu publishen, was wahrscheinlich aber auch eher ein Fehler beim Übertragen war oder so.) |
|||
(39 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
= Introduction = |
|||
Python is a versatile, easy-to-learn, usually interpreted programming language. It offers a wide range of libraries for scientific tasks and visualization. Python is the de facto standard interface for applications of machine learning. Python can be used in particular as an open source alternative for tasks that have usually been used for Matlab. |
|||
== Introduction == |
|||
= Installation and Versions = |
|||
Python is a versatile, easy-to-learn, interpreted programming language. It offers a wide range of libraries for scientific tasks and visualization. Python counts to the best languages for machine learning. Python can be used in particular as an open source alternative for tasks that have usually been used for Matlab. |
|||
Python is available on all systems. Either as system Python, which comes bundled with the operating system, or via Lmod software modules. Installation is not required. |
|||
== |
== Installation and Versions == |
||
Python is available on all systems. With <code>python --version</code> you can see the currently active default python version. In general, you can choose from various types of python installations: |
|||
System Python is available in different versions, typically the default system Python is too old for most users and applications. Newer versions are therefore installed alongside the standard version. You can access a specific Python version by specifying the version in the Python command. |
|||
* '''System python:''' This python version comes together with the operating system and is available upon login to the cluster. Other python versions might be installed along with it. All versions can be seen with |
|||
*: <code>ls /usr/bin/python[0-9].*[0-9] | sort -V | cut -d"/" -f4 | xargs</code> |
|||
*: They can change over time. You can access a specific Python version by specifying the version in the Python command. |
|||
* '''[[Environment_Modules | Software module]]:''' Available versions can be identified via |
|||
*: <syntaxhighlight lang="bash"> |
|||
module avail devel/python |
|||
</syntaxhighlight> |
|||
* '''Python distributions and virtual environments:''' By using python distributions such as Anaconda, you can easily install the needed python version into a virtual environment. For the use of conda on bwHPC clusters, please refer to [[Development/Conda|Conda]]. Alternatively, you can use more python specific tools for installing python. Some options are listed in [[#Virtual Environments and Package Management | Virtual Environments and Package Management]] |
|||
* '''[[Development/Containers | Container]]:''' Containers can contain their own python installation. Keep this in mind when you are working with containers provided by others. |
|||
== Running Python Code == |
|||
On bwUniCluster, different versions are currently available, <code>ls /usr/bin/python[0-9].*[0-9] | sort -V | cut -d"/" -f4 | xargs</code> results in: <code>python2.7 python3.6 python3.8 python3.9 python3.11</code>. |
|||
There are three ways to run Python commands: |
|||
Please note, that these exact versions will change over time and differ from site to site! |
|||
* Within a '''terminal''' by executing the comand <code>python</code>. This starts a Python shell, where all commands are evaluated by the Python interpreter. |
|||
<source lang="bash"> |
|||
* Within a '''script''' (file ends with ''.py'' and can be run with <code>python myProgram.py</code>) |
|||
$ python --version # This is system default Python |
|||
* Within a '''notebook''' (file ends with .ipynb). You can use other programming languages and markdown within a notebook next to your python code. Besides software development itself, teaching, prototyping and visualization are good use cases for notebooks as well. |
|||
Python 3.6.8 |
|||
$ python3.11 --version |
|||
Python 3.11.2 |
|||
</source> |
|||
== |
== Development Environments == |
||
Python is also offered via software modules. Available versions can be identified via: |
|||
<source lang="bash"> |
|||
$ module avail devel/python |
|||
</source> |
|||
Development Environments are usually more comfortable than running code directly from the shell. Some common options are: |
|||
A specific version of Python can then be chosen e.g. as follows: |
|||
<source lang="bash"> |
|||
$ module load devel/python/3.12.3_gnu_13.3 |
|||
$ python --version |
|||
Python 3.12.3 |
|||
</source> |
|||
* [[Jupyter]] |
|||
== Python Distributions == |
|||
* [[Development/VS_Code | VS Code]] |
|||
For the usage of Python we strongly recommend <b>not to install</b> own Python versions, e.g. via distributions like Anaconda. However, there are use cases where the use of e.g. conda is beneficial or, depending on the scientific community, a standard approach to distribute Python packages. For the use of conda on bwHPC clusters, please refer to [[ Conda ]]. |
|||
* PyCharm |
|||
== Virtual Environments and Package Management == |
|||
= Usage = |
|||
Packages contain a set of functions that offer additional functionality. A package can be installed by using a package manager. Virtual environments prevent conflicts between different Python packages by using separate installation directories. |
|||
There are two ways to run Python commands: |
|||
At least one virtual environment should be defined per project. This way, it is clear which packages are needed by a specific project. All virtual environments allow to save the corresponding packages with their specific version numbers to a file. This allows to reinstall them in another place and therefore improves the reproducibility of projects. Furthermore, it makes finding and removing packages, that aren't needed anymore, easier. |
|||
# Interactive Mode |
|||
# Script Mode |
|||
=== Overview === |
|||
In order to start the interactive mode, simply run the <code>python</code> command. |
|||
The following table provides an overview of common tools in the field of virtual environments and package management. The main differences between the various options are highlighted. After deciding on a specific tool, it can be installed by following the given link. |
|||
This starts a Python shell, where all commands are evaluated by the Python interpreter. |
|||
To make it short, if you plan to use... |
|||
* ...Python only: |
|||
** venv is the most basic option. Other options build upon it. |
|||
** poetry is widely used and offers a broad set of functionality |
|||
** uv is the latest option and much faster than poetry while offering the same (or more) functionality. |
|||
* ...Python + Conda: |
|||
** We wouldn't recommend it but if you want to use conda only: Install the conda packages first into the conda environment and afterwards the python packages. Otherwise, problems might arise. |
|||
** For a faster and more up to date solution, choose pixi. |
|||
{| class="wikitable" |
|||
Script mode basically means, that all Python commands are stored in a text file with the extension <b>.py</b>.<br/> |
|||
|- style="text-align:center;" |
|||
The program will be executed via |
|||
! Tool |
|||
<code lang="bash"> |
|||
! Description |
|||
python myProgram.py |
|||
! Can install python versions |
|||
</code> |
|||
! Installs packages from PyPI |
|||
! Installs packages from conda |
|||
! Dependency Resolver |
|||
! Dependency Management |
|||
! Creates Virtual Environments |
|||
! Supports building, packaging and publishing code (to PyPI) |
|||
|- |
|||
| pyenv |
|||
| Manages python versions on your system. |
|||
| yes |
|||
| no |
|||
| no |
|||
| no |
|||
| no |
|||
| no |
|||
| no |
|||
|- |
|||
| pip |
|||
| For installing python packages. |
|||
| no |
|||
| yes |
|||
| no |
|||
| yes |
|||
| no |
|||
| no |
|||
| no |
|||
|- |
|||
| venv |
|||
| For installing and managing python packages. Part of Python's standard library. |
|||
| no |
|||
| no |
|||
| no |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| no |
|||
|- |
|||
| poetry |
|||
| For installing and managing python packages. Install it with pipx. |
|||
| no |
|||
| yes |
|||
| no |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
|- |
|||
| pipx |
|||
| For installing and running python applications (like poetry) globally while having them in isolated environments. It is useful for keeping applications globally available and at the same time separated in their own virtual environments. Use it when the installation instructions of an application offer you this way of installation. |
|||
| no |
|||
| no |
|||
| no |
|||
| yes |
|||
| yes |
|||
| yes (only for single applications) |
|||
| no |
|||
|- |
|||
| uv |
|||
| Replaces poetry, pyenv, pip etc. and is very fast (https://www.loopwerk.io/articles/2025/uv-keeps-getting-better/) |
|||
| yes |
|||
| yes |
|||
| no |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
|- |
|||
| pixi |
|||
| For installing and managing python as well as conda packages. Uses uv in the background |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
| yes |
|||
|} |
|||
=== Pip === |
|||
For teaching purposes, code prototyping and visualization, the use of Jupyter notebooks is advantageous. Further information about interactive supercomputing and the use of Jupyter can be found at [[Jupyter]]. |
|||
The standard package manager under Python is <code>pip</code>. It can be used to install, update and delete packages. Pip can be called directly or via <code>python -m pip</code>. The standard repository from which packages are obtained is PyPI (https://pypi.org/). When a package depends on others, they are automatically installed as well. |
|||
= Package Manager= |
|||
In the following, the most common pip commands are shown exemplarily. Packages should always be installed within virtual environments to avoid conflicting installations. If you decide to not use a virtual environment, the install commands have to be accomplished by a <code>--user</code> flag or controlled via environment variables. |
|||
<b>Installation of packages</b><br/> |
|||
The functionality of Python is extended via modules. The standard package manager under Python is <code>pip</code>. It can be used to install, update and delete packages. <code>pip</code> can be called directly or via <code>python -m pip</code>. The standard repository from which packages are obtained is PyPI (https://pypi.org/). Package dependencies are automatically installed. |
|||
<syntaxhighlight lang="python"> |
|||
pip install pandas # Installs the latest compatible version of pandas and its required dependencies |
|||
pip install pandas=1.5.3 # Installs exact version |
|||
pip install pandas>=1.5.3 # Installs version newer or equal to 1.5.3 |
|||
</syntaxhighlight> |
|||
The packages from PyPI usually consist of precompiled libraries. However, <code>pip</code> is also capable of creating packages from source code. However, this may require the C/C++ compiler and other dependencies needed to build the libraries. In the example, pip obtains the source code of matplotlib from github.com, installs its dependencies, compiles the library and installs it: |
|||
Examples: |
|||
<syntaxhighlight lang="python"> |
|||
pip install git+https://github.com/matplotlib/matplotlib |
|||
</syntaxhighlight> |
|||
<b>Upgrade packages</b><br/> |
|||
<syntaxhighlight lang="python"> |
|||
pip install --upgrade pandas # Updates the library if update is available |
|||
</syntaxhighlight> |
|||
<b>Removing packages</b><br/> |
|||
<syntaxhighlight lang="python"> |
|||
pip uninstall pandas # Removes pandas |
|||
</syntaxhighlight> |
|||
<b>Show packages</b><br/> |
|||
<syntaxhighlight lang="python"> |
|||
pip list # Shows the installed packages |
|||
pip freeze # Shows the installed packages and their versions |
|||
</syntaxhighlight> |
|||
<b>Save State</b><br/> |
|||
To allow for reproducibility it is important to provide information about the full list of packages and their exact versions [https://pip.pypa.io/en/stable/topics/repeatable-installs/ see version pinning]. |
|||
<syntaxhighlight lang="python"> |
|||
pip freeze > requirements.txt # redirect package and version information to a textfile |
|||
pip install -r requirements.txt # Installs all packages that are listed in the file |
|||
</syntaxhighlight> |
|||
=== Venv === |
|||
* <code>pip install matplotlib</code> installs the visualization library matplotlib and its required dependencies |
|||
* <code>pip uninstall matplotlib</code> uninstalls matplotlib |
|||
* <code>pip install --upgrade matplotlib</code> updates the library if necessary |
|||
* <code>pip list</code> shows the installed packages and their versions |
|||
* <code>pip freeze</code> shows the installed packages and their versions, the output can be redirected to a `requirements.txt` file. Only recommended if version pinning (https://pip.pypa.io/en/stable/topics/repeatable-installs/) is explicitly desired. |
|||
The module <code>venv</code> enables the creation of a virtual environment and is a standard component of Python. Creating a <code>venv</code> means that a folder is created which contains a separate copy of the Python binary file as well as <code>pip</code> and <code>setuptools</code>. After activating the <code>venv</code>, the binary file in this folder is used when <code>python</code> or <code>pip</code> is called. This folder is also the installation target for other Python packages. |
|||
The packages from PyPI usually consist of precompiled libraries. However, <code>pip</code> is also capable of creating packages from source code. However, this may require the C/C++ compiler and other dependencies needed to build the libraries. |
|||
==== Creation ==== |
|||
* <code>pip install git+https://github.com/matplotlib/matplotlib</code> obtains the source code of matplotlib from github.com, installs its dependencies, compiles the library and installs it |
|||
Create, activate, install software, deactivate: |
|||
Several external packages are usually required for a software project. It is advisable to create the file <code>requirements.txt</code>, i.e. a text file with all dependencies. |
|||
<syntaxhighlight lang="bash"> |
|||
python3.11 -m venv myEnv # Create venv |
|||
source myEnv/bin/activate # Activate venv |
|||
pip install --upgrade pip # Update of the venv-local pip |
|||
pip install <list of packages> # Install packages/modules |
|||
deactivate |
|||
</syntaxhighlight> |
|||
Install list of software: |
|||
* <code>pip install -r requirements.txt</code> installs these packages in one go |
|||
<syntaxhighlight lang="bash"> |
|||
pip install -r requirements.txt # Install packages/modules |
|||
</syntaxhighlight> |
|||
==== Usage ==== |
|||
= Virtual Environments = |
|||
To use the virtual environment after all dependencies have been installed there, it is sufficient to simply activate it: |
|||
Virtual environments allow Python packages to be installed separately in a separate installation directory for a specific application instead of installing them globally. This prevents version conflicts, promotes clarity as to which packages are required for which software and prevents the home directory from being cluttered with libraries that are not (or no longer) required. |
|||
<syntaxhighlight lang="bash"> |
|||
== Creation == |
|||
source myEnv/bin/activate # Activate venv |
|||
</syntaxhighlight> |
|||
With <code>venv</code> activated the terminal prompt will reflect that accordingly: |
|||
<syntaxhighlight lang="bash"> |
|||
(myEnv) $ |
|||
</syntaxhighlight> |
|||
It is no longer necessary to specify the Python version, the simple command <code>python</code> starts the Python version that was used to create the virtual environment.<br/> |
|||
You can check, which Python version is in use via: |
|||
<syntaxhighlight lang="bash"> |
|||
(myEnv) $ which python |
|||
</path/to/project>/myEnv/bin/python |
|||
</syntaxhighlight> |
|||
== |
=== Poetry === |
||
==== Creation ==== |
|||
= Best Practice = |
|||
When you want to create a virtual environment for an already existing project, you can go to the top directory and run |
|||
Always use virtual environments |
|||
<syntaxhighlight lang="bash"> |
|||
poetry init # Create virtual environment |
|||
</syntaxhighlight> |
|||
Otherwise start with the demo project: |
|||
<syntaxhighlight lang="bash"> |
|||
poetry new poetry-demo |
|||
</syntaxhighlight> |
|||
You can set the allowed python versions in the pyproject.toml. To switch between python installations on your sytem, you can use |
|||
<syntaxhighlight lang="bash"> |
|||
poetry env use python3.11 |
|||
</syntaxhighlight> |
|||
==== Usage ==== |
|||
Do's and don'ts |
|||
Install and update packages |
|||
<syntaxhighlight lang="bash"> |
|||
poetry install <package_name> |
|||
poetry update # Update to latest versions of packages |
|||
</syntaxhighlight> |
|||
To execute something within the virtual environment: |
|||
<syntaxhighlight lang="bash"> |
|||
poetry run <command> |
|||
</syntaxhighlight> |
|||
Helpful links: |
|||
* [https://python-poetry.org/docs/managing-environments/#activating-the-environment Activate Environment] |
|||
Helpful commands |
|||
<syntaxhighlight lang="bash"> |
|||
poetry env info # show environment information |
|||
poetry env list # list all virtual environments associated with the current project |
|||
poetry env list --full-path |
|||
poetry env remove # delete virtual environment |
|||
</syntaxhighlight> |
|||
=== uv === |
|||
==== Creation ==== |
|||
With uv you can create two types of new projects. Either an application (default) or a library. |
|||
→ '''[https://docs.astral.sh/uv/concepts/projects/ projects]''' |
|||
<syntaxhighlight lang="bash"> |
|||
uv init <application_name> |
|||
# If you want to create a python package: |
|||
uv init --package <application_name> |
|||
</syntaxhighlight> |
|||
When you have an existing project, you can create a virtual environment at .venv with a specific python version as follows: |
|||
<syntaxhighlight lang="bash"> |
|||
uv venv --python 3.11 |
|||
</syntaxhighlight> |
|||
A specific name or path can be given instead of "venv" as well. If the python version is not available on the system, uv downloads it. |
|||
==== Usage ==== |
|||
The currently active environment is saved in the environment variable <code>VIRTUAL_ENV</code>. The environment can be activated and deactivated as follows: |
|||
<syntaxhighlight lang="bash"> |
|||
source .venv/bin/activate |
|||
deactivate |
|||
</syntaxhighlight> |
|||
If you activated the virtual environment, you can install packagages as usual. Otherwise, you need to add "uv" before the command to run it within the virtual environment: |
|||
<syntaxhighlight lang="bash"> |
|||
uv pip install <package_name> |
|||
</syntaxhighlight> |
|||
To execute a python file within the virtual environment: |
|||
<syntaxhighlight lang="bash"> |
|||
uv run <file.py> |
|||
</syntaxhighlight> |
|||
If one project has multiple different groups of packages that are used, it could make sense to look into uv workspaces: |
|||
→ '''[https://docs.astral.sh/uv/concepts/projects/workspaces/ workspaces]''' |
|||
=== Pixi === |
|||
==== Creation ==== |
|||
With uv you can create two types of new projects. Either an application (default) or a library. |
|||
→ '''[https://pixi.sh/latest/python/tutorial/ Python Tutorial]''' |
|||
<syntaxhighlight lang="bash"> |
|||
pixi init <project_name> --format pyproject |
|||
</syntaxhighlight> |
|||
==== Usage ==== |
|||
Add a new package to the environment: |
|||
<syntaxhighlight lang="bash"> |
|||
# Get it from conda: |
|||
pixi add <package_name> |
|||
# Get it from PyPi |
|||
pixi add <package_name> --pypi |
|||
</syntaxhighlight> |
|||
To execute a command within the virtual environment: |
|||
<syntaxhighlight lang="bash"> |
|||
pixi run <command> |
|||
</syntaxhighlight> |
|||
== Workflow Management Systems == |
|||
There are a lot of different workflow management systems. One example is [https://snakemake.readthedocs.io/en/stable/index.html Snakemake] which is often used in the field of biology/medicine. Two use cases for snakemake workflows would be: |
|||
* Use an existing workflow to analyze data. |
|||
* Create your own workflow to make your research more reproducible. |
|||
Leaving the python world, a common choice for bioinformaticians would be Nextflow as there is a strong community that focuses on standardisation. Those more standardised pipelines can be found at the [https://nf-co.re/pipelines/ nf-core website]. |
|||
In other research fields, other workflow management systems might be more common. |
|||
== Best Practices == |
|||
* Always use virtual environments! Use one environment per project. |
|||
* If a new or existing Python project is to be created or used, the following procedure is recommended: |
|||
# Version the Python source files and the <code>requirements.txt</code> file with a version control system, e.g. git. Exclude unnecessary folders and files like for example <code>venv</code> via an entry in the ignore file, for example <code>.gitignore</code>. |
|||
# Create and activate a virtual environment. |
|||
# Use specialized number crunching python modules (e.g. numpy and scipy), don't use plain python for serious caluclations |
|||
## check if optimized compiled modules are available on the cluster (numpy, scipy) |
|||
# Update pip <code>pip install --upgrade pip</code>. |
|||
# Install all required packages via the <code>requirements.txt</code> file in the case of venv. Or by using the corresponding command of your chosen tool. |
|||
* List or dictionary comprehensions are to be prefered over loops as they are in general faster. |
|||
* Be aware of the differences between references, shallow and deep copies. |
|||
* Do not parallelize by hand but use libraries were possible (Dask, ...). |
|||
<!-- |
|||
== Example == |
== Example == |
||
== Do's and don'ts == |
|||
Using Conda and Pip/Venv together |
|||
In some cases, Pip/Venv might be the preferred method for installing an environment. This could be because a central Python package comes with installation instructions that only show Pip as a supported option (like Tensorflow) or the use of projects which were written with the use of Pip in mind, for example by offering a requirements.txt and a rewrite with testing is not feasable. |
|||
In this case, it makes sense to use Conda as a replacement for Venv and use it to supply the virtual enviroment with the required Python version. After activating the environment, Pip will we available and refer to this Python enviroment. |
|||
--> |
Latest revision as of 13:36, 6 October 2025
Introduction
Python is a versatile, easy-to-learn, interpreted programming language. It offers a wide range of libraries for scientific tasks and visualization. Python counts to the best languages for machine learning. Python can be used in particular as an open source alternative for tasks that have usually been used for Matlab.
Installation and Versions
Python is available on all systems. With python --version
you can see the currently active default python version. In general, you can choose from various types of python installations:
- System python: This python version comes together with the operating system and is available upon login to the cluster. Other python versions might be installed along with it. All versions can be seen with
ls /usr/bin/python[0-9].*[0-9] | sort -V | cut -d"/" -f4 | xargs
- They can change over time. You can access a specific Python version by specifying the version in the Python command.
- Software module: Available versions can be identified via
module avail devel/python
- Python distributions and virtual environments: By using python distributions such as Anaconda, you can easily install the needed python version into a virtual environment. For the use of conda on bwHPC clusters, please refer to Conda. Alternatively, you can use more python specific tools for installing python. Some options are listed in Virtual Environments and Package Management
- Container: Containers can contain their own python installation. Keep this in mind when you are working with containers provided by others.
Running Python Code
There are three ways to run Python commands:
- Within a terminal by executing the comand
python
. This starts a Python shell, where all commands are evaluated by the Python interpreter. - Within a script (file ends with .py and can be run with
python myProgram.py
) - Within a notebook (file ends with .ipynb). You can use other programming languages and markdown within a notebook next to your python code. Besides software development itself, teaching, prototyping and visualization are good use cases for notebooks as well.
Development Environments
Development Environments are usually more comfortable than running code directly from the shell. Some common options are:
Virtual Environments and Package Management
Packages contain a set of functions that offer additional functionality. A package can be installed by using a package manager. Virtual environments prevent conflicts between different Python packages by using separate installation directories.
At least one virtual environment should be defined per project. This way, it is clear which packages are needed by a specific project. All virtual environments allow to save the corresponding packages with their specific version numbers to a file. This allows to reinstall them in another place and therefore improves the reproducibility of projects. Furthermore, it makes finding and removing packages, that aren't needed anymore, easier.
Overview
The following table provides an overview of common tools in the field of virtual environments and package management. The main differences between the various options are highlighted. After deciding on a specific tool, it can be installed by following the given link. To make it short, if you plan to use...
- ...Python only:
- venv is the most basic option. Other options build upon it.
- poetry is widely used and offers a broad set of functionality
- uv is the latest option and much faster than poetry while offering the same (or more) functionality.
- ...Python + Conda:
- We wouldn't recommend it but if you want to use conda only: Install the conda packages first into the conda environment and afterwards the python packages. Otherwise, problems might arise.
- For a faster and more up to date solution, choose pixi.
Tool | Description | Can install python versions | Installs packages from PyPI | Installs packages from conda | Dependency Resolver | Dependency Management | Creates Virtual Environments | Supports building, packaging and publishing code (to PyPI) |
---|---|---|---|---|---|---|---|---|
pyenv | Manages python versions on your system. | yes | no | no | no | no | no | no |
pip | For installing python packages. | no | yes | no | yes | no | no | no |
venv | For installing and managing python packages. Part of Python's standard library. | no | no | no | yes | yes | yes | no |
poetry | For installing and managing python packages. Install it with pipx. | no | yes | no | yes | yes | yes | yes |
pipx | For installing and running python applications (like poetry) globally while having them in isolated environments. It is useful for keeping applications globally available and at the same time separated in their own virtual environments. Use it when the installation instructions of an application offer you this way of installation. | no | no | no | yes | yes | yes (only for single applications) | no |
uv | Replaces poetry, pyenv, pip etc. and is very fast (https://www.loopwerk.io/articles/2025/uv-keeps-getting-better/) | yes | yes | no | yes | yes | yes | yes |
pixi | For installing and managing python as well as conda packages. Uses uv in the background | yes | yes | yes | yes | yes | yes | yes |
Pip
The standard package manager under Python is pip
. It can be used to install, update and delete packages. Pip can be called directly or via python -m pip
. The standard repository from which packages are obtained is PyPI (https://pypi.org/). When a package depends on others, they are automatically installed as well.
In the following, the most common pip commands are shown exemplarily. Packages should always be installed within virtual environments to avoid conflicting installations. If you decide to not use a virtual environment, the install commands have to be accomplished by a --user
flag or controlled via environment variables.
Installation of packages
pip install pandas # Installs the latest compatible version of pandas and its required dependencies
pip install pandas=1.5.3 # Installs exact version
pip install pandas>=1.5.3 # Installs version newer or equal to 1.5.3
The packages from PyPI usually consist of precompiled libraries. However, pip
is also capable of creating packages from source code. However, this may require the C/C++ compiler and other dependencies needed to build the libraries. In the example, pip obtains the source code of matplotlib from github.com, installs its dependencies, compiles the library and installs it:
pip install git+https://github.com/matplotlib/matplotlib
Upgrade packages
pip install --upgrade pandas # Updates the library if update is available
Removing packages
pip uninstall pandas # Removes pandas
Show packages
pip list # Shows the installed packages
pip freeze # Shows the installed packages and their versions
Save State
To allow for reproducibility it is important to provide information about the full list of packages and their exact versions see version pinning.
pip freeze > requirements.txt # redirect package and version information to a textfile
pip install -r requirements.txt # Installs all packages that are listed in the file
Venv
The module venv
enables the creation of a virtual environment and is a standard component of Python. Creating a venv
means that a folder is created which contains a separate copy of the Python binary file as well as pip
and setuptools
. After activating the venv
, the binary file in this folder is used when python
or pip
is called. This folder is also the installation target for other Python packages.
Creation
Create, activate, install software, deactivate:
python3.11 -m venv myEnv # Create venv
source myEnv/bin/activate # Activate venv
pip install --upgrade pip # Update of the venv-local pip
pip install <list of packages> # Install packages/modules
deactivate
Install list of software:
pip install -r requirements.txt # Install packages/modules
Usage
To use the virtual environment after all dependencies have been installed there, it is sufficient to simply activate it:
source myEnv/bin/activate # Activate venv
With venv
activated the terminal prompt will reflect that accordingly:
(myEnv) $
It is no longer necessary to specify the Python version, the simple command python
starts the Python version that was used to create the virtual environment.
You can check, which Python version is in use via:
(myEnv) $ which python
</path/to/project>/myEnv/bin/python
Poetry
Creation
When you want to create a virtual environment for an already existing project, you can go to the top directory and run
poetry init # Create virtual environment
Otherwise start with the demo project:
poetry new poetry-demo
You can set the allowed python versions in the pyproject.toml. To switch between python installations on your sytem, you can use
poetry env use python3.11
Usage
Install and update packages
poetry install <package_name>
poetry update # Update to latest versions of packages
To execute something within the virtual environment:
poetry run <command>
Helpful links:
Helpful commands
poetry env info # show environment information
poetry env list # list all virtual environments associated with the current project
poetry env list --full-path
poetry env remove # delete virtual environment
uv
Creation
With uv you can create two types of new projects. Either an application (default) or a library.
→ projects
uv init <application_name>
# If you want to create a python package:
uv init --package <application_name>
When you have an existing project, you can create a virtual environment at .venv with a specific python version as follows:
uv venv --python 3.11
A specific name or path can be given instead of "venv" as well. If the python version is not available on the system, uv downloads it.
Usage
The currently active environment is saved in the environment variable VIRTUAL_ENV
. The environment can be activated and deactivated as follows:
source .venv/bin/activate
deactivate
If you activated the virtual environment, you can install packagages as usual. Otherwise, you need to add "uv" before the command to run it within the virtual environment:
uv pip install <package_name>
To execute a python file within the virtual environment:
uv run <file.py>
If one project has multiple different groups of packages that are used, it could make sense to look into uv workspaces:
Pixi
Creation
With uv you can create two types of new projects. Either an application (default) or a library.
pixi init <project_name> --format pyproject
Usage
Add a new package to the environment:
# Get it from conda:
pixi add <package_name>
# Get it from PyPi
pixi add <package_name> --pypi
To execute a command within the virtual environment:
pixi run <command>
Workflow Management Systems
There are a lot of different workflow management systems. One example is Snakemake which is often used in the field of biology/medicine. Two use cases for snakemake workflows would be:
- Use an existing workflow to analyze data.
- Create your own workflow to make your research more reproducible.
Leaving the python world, a common choice for bioinformaticians would be Nextflow as there is a strong community that focuses on standardisation. Those more standardised pipelines can be found at the nf-core website. In other research fields, other workflow management systems might be more common.
Best Practices
- Always use virtual environments! Use one environment per project.
- If a new or existing Python project is to be created or used, the following procedure is recommended:
- Version the Python source files and the
requirements.txt
file with a version control system, e.g. git. Exclude unnecessary folders and files like for examplevenv
via an entry in the ignore file, for example.gitignore
. - Create and activate a virtual environment.
- Use specialized number crunching python modules (e.g. numpy and scipy), don't use plain python for serious caluclations
- check if optimized compiled modules are available on the cluster (numpy, scipy)
- Update pip
pip install --upgrade pip
. - Install all required packages via the
requirements.txt
file in the case of venv. Or by using the corresponding command of your chosen tool.
- List or dictionary comprehensions are to be prefered over loops as they are in general faster.
- Be aware of the differences between references, shallow and deep copies.
- Do not parallelize by hand but use libraries were possible (Dask, ...).