Sometimes I download a Python script (from a trusted source), and can't run it because of missing dependencies, which I have to install one by one (no requirements.txt
is provided). I'm looking for a way to automate this process. It's similar to this question, but I'd like to infer the requirements automatically. I.e. given the script, install all the packages it's importing.
If myscript.py
looks like:
import pandas
import tensorflow as tf
from keras.models import Sequential
Then after running the script (e.g. bash extract_requirements.sh myscript.py
) pandas
, tensorflow
, and keras
will be installed.
Of course, a script can call another script, which has its own dependencies, package names don't always match to import names etc. So it's not a perfect solution, but better than nothing.
What I'm using now is a command-line script:
#!/env bash
set -u
usage() {
echo "$0" '[-d] <MY_SCRIPT>'
cat <<-EOF
options:
-d Dry-run. Print package names without installing.
EOF
exit 1;
}
(( $# == 0 )) && usage
dry=0
if [[ "$1" == '-d' ]]; then
dry=1
shift
fi
(( $# != 1 )) && usage
script="$1"
imports1=$(egrep '^\s*from\s+[a-zA-Z_.-]+\simport' "$script" | cut -f2 -d' ' | cut -f1 -d'.')
imports2=$(egrep '^\s*import\s+[a-zA-Z_-]+' "$script" | cut -f2 -d' ')
all=$(printf "$imports1\n$imports2" | sort -u)
if (( dry )); then
echo "$all" | xargs -L 1 echo
else
echo "$all" | xargs -L 1 sudo pip install
fi
set +u
I was wondering if I'm missing some import
cases, and more importantly, whether there's a simpler, more python-ic, solution.