Home] [About] [Posts] [Resources]
dir: Home /
Posts /
Jupyter - One-Liner pip Install
published-date: 20 Oct 2024 16:22 +0700
categories: [misc] [quickie]
tags: [python] [jupyter]
When working with jupyter notebook, you might come across the need to install external packages in your environment with your preferred package manager such as pip
. Say you’re not using conda or other environment managers, which your option is to install packages by invoking bash from the notebook itself. I find this approach to be more portable than installing from requirements.txt
dump from pip list
spec, which can be a hassle when you’re constrained to use google colab.
Problem though when we invoke pip <package-name>
there are time wasted since pip will need to check whether the package is already installed every time we run the cell containing pip installs. To combat this we can perform check with pkgutil
and install accordingly with a one-liner.
1! if [ $(python3 -c "import pkgutil; print(1 if pkgutil.find_loader(\"<import-module-name>\") else 0)") = "0" ]; then pip install <package-name>
Be aware that module name might differ from the package name containing that module.
If there are more than one package of interest, then we can wrap them as bash function.
1! function pipckpkg () { echo "checking module $1 from package $2"; if [ $(python3 -c "import pkgutil; print(1 if pkgutil.find_loader(\"$1\") else 0)") = "0" ]; then pip install -U $2; else echo "skipping $2";fi; } ;\
2! pipckpkg "openpyxl" "openpyxl" ;\
3! pipckpkg "kaleido" "kaleido" ;\
4! pipckpkg "pptx" "python-pptx" ;\
5! pipckpkg "pypdf" "pypdf"
Note the trailing semicolon and backward-slash, as the function definition only exists on that call.
Built with Hugo | previoip (c) 2024