Skip to content

Instantly share code, notes, and snippets.

@kwatch
Last active May 8, 2016 15:34
Show Gist options
  • Save kwatch/a39166a56dd7dba5c7f95deed9371d28 to your computer and use it in GitHub Desktop.
Save kwatch/a39166a56dd7dba5c7f95deed9371d28 to your computer and use it in GitHub Desktop.
pydiet.sh -- remove unnecessary files from Python directory interactively
#!/bin/sh
###
### pydiet.sh -- remove unnecessary files from Python directory interactively
###
### Feature:
### * remove test script files (ex: python2.7/test/*)
### * remove *.pyo files (ex: python2.7/**/*.pyo)
### * remove *.opt-[12].pyc files (Python 3.5 or later)
###
### Usage: sh pydiet.sh <directory>
###
### Example:
### $ curl -O https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tar.xz
### $ tar xf Python-3.5.1.tar.xz
### $ cd Python-3.5.1/
### $ ./configure --prefix=$HOME/python/3.5.1
### $ make && make install
### $ sh pydiet.sh $HOME/python/3.5.1 # ex: 139,736KB -> 64,420KB
###
_cmd() {
echo '$' $1
if eval $1; then
return 0
else
echo "** FAILED: $1" 1>&2
return 1
fi
}
_du_sk() {
local dir=$1
local label=$2
echo "*** $label"
_cmd "du -sk $dir"
}
_diet_test() {
local libdir=$1
local testdir="$libdir/test"
local input
printf "*** Remvoe files under $testdir? [Y/n]: "
read input; [ -z "$input" ] && input="y"
case "$input" in
y*|Y*)
_cmd "mv $testdir/__init__.py $testdir.tmp.py"
#_cmd "rm -rf $testdir/*" # expands filenames unexpectedly
#_cmd 'rm -rf '$testdir/'*' # expands filenames unexpectedly
echo '$ rm -rf '$testdir/'*'
rm -rf $testdir/*
_cmd "mv $testdir.tmp.py $testdir/__init__.py"
return 0
;;
esac
return 1
}
_diet_pyo() {
local libdir=$1
local input
printf "*** Remove *.pyo or *.opt-[12].pyc files under $libdir? [Y/n]: "
read input; [ -z "$input" ] && input="y"
case "$input" in
y*|Y*)
_cmd "find $libdir -name '*.pyo' | xargs rm -f"
_cmd "find $libdir -name '*.opt-?.pyc' | xargs rm -f" # Python 3.5 or later
return 0
;;
esac
return 1
}
_main() {
basedir=$1
if [ -z "$basedir" ]; then
echo "Usage: sh diet.sh <basedir>"
else
libdir=`echo "$basedir/lib/python[23].*"`
_du_sk $basedir "before"
_diet_test $libdir && _du_sk $basedir "after"
_diet_pyo $libdir && _du_sk $basedir "after"
fi
}
_main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment