Last active
May 1, 2025 17:59
-
-
Save preeteshjain/cc20d78585ffa1cb5a9aa477fe872472 to your computer and use it in GitHub Desktop.
Bash function to install & run Black, isort, autoflake with virtual-env check on any Python file/project. Add this to your bash aliases for easy access.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
format_python() { | |
if [ $# -lt 1 ]; then | |
echo "Usage: format_python <path> [<path> ...]" | |
return 1 | |
fi | |
# Virtual-env check | |
if [ -z "$VIRTUAL_ENV" ]; then | |
echo "Warning: no Python virtualenv detected. You may want to activate one." | |
read -r -p "Continue anyway? (y/N) " answer | |
case "$answer" in | |
[Yy]|[Yy][Ee][Ss]) | |
echo "→ Proceeding without virtualenv." | |
;; | |
*) | |
echo "Aborted. Activate a virtualenv and try again." | |
return 1 | |
;; | |
esac | |
fi | |
# Ensure tools are installed | |
local pkgs=(black isort autoflake) | |
for pkg in "${pkgs[@]}"; do | |
if ! command -v "$pkg" >/dev/null 2>&1; then | |
echo "→ Installing $pkg..." | |
pip install "$pkg" | |
fi | |
done | |
# Run formatters in order | |
echo "→ Running autoflake..." | |
autoflake \ | |
--remove-all-unused-imports \ | |
--recursive \ | |
--remove-unused-variables \ | |
--in-place \ | |
"$@" | |
echo "→ Running isort..." | |
isort "$@" | |
echo "→ Running black..." | |
black "$@" | |
echo "🎉 Formatting complete." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment