Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Created November 19, 2024 07:26
Show Gist options
  • Save miraculixx/61a6a265762a919bfdb256c12792997a to your computer and use it in GitHub Desktop.
Save miraculixx/61a6a265762a919bfdb256c12792997a to your computer and use it in GitHub Desktop.
try a python package in its own venv
#!/bin/bash
function setup() {
python -m venv .pytry
source .pytry/bin/activate
pip install $packages
}
function tryimport() {
toimport=$1
python -i -c "import $toimport; print($toimport)"
}
function cleanup {
deactivate
[[ $keep -ne 1 ]] && rm -rf .pytry
}
# Parse command-line arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--keep)
keep=1
shift # Move to the next argument
;;
*)
packages+=("$1") # Collect packages
shift # Move to the next argument
;;
esac
done
setup >/dev/null 2>&1
tryimport ${packages[0]}
cleanup
@miraculixx
Copy link
Author

Usage:

# pytry [--keep] package [packages...]
$ chmod +x pytry
$ ./pytry pandas
<module 'pandas' from '/home/user/.pytry/lib/python3.10/site-packages/pandas/__init__.py'>
>>> 

It will create and delete a new venv in the current directory at $PWD/.pytry. Then it will pip install all packages listed, and import the first. Upon exit(), the venv is deleted. Specify --keep to keep .pytry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment