Skip to content

Instantly share code, notes, and snippets.

@bersace
Last active December 30, 2015 15:27
Show Gist options
  • Save bersace/6b09e6bff8fb53bf64d2 to your computer and use it in GitHub Desktop.
Save bersace/6b09e6bff8fb53bf64d2 to your computer and use it in GitHub Desktop.
Script python exécutable et sourceable par bash
#!/bin/bash
## -*- python -*-
#
# This python script is callable and sourceable by bash.
#
# lint python with: flake8 --ignore=E225,E265 py.sh
# lint bash with: sed '/^## END BASH/,$d' py.sh | shellcheck -
## In bash, declare a variable script, assign value "#". In python, declare a
## variable scriptd, assign a heredoc containing the bash script.
# shellcheck disable=SC2034
script=""" "
## BEGIN BASH
# my_sh_func [ARG ...]
# Echo arguments
#
# my_sh_func toto
#
my_sh_func() {
echo $*
}
if [[ ${BASH_SOURCE[0]} = $0 ]]; then
if declare -f -- "${1-}" >&2; then
# When $1 is a bash function, call it and exit.
set -eux
$*
exit 0
else
# Any other argument is passed to python script.
exec python3 ${BASH_SOURCE[0]} $*
fi
else
echo ${BASH_SOURCE[0]} sourced
return 0
fi
## Assert this statement is not reached in bash.
exit 1
## END BASH
""" # " # Close quote for bash syntax highlighting.
## Drop script variable, and begin python script as usual.
del script
import sys
print(sys.argv)
@bersace
Copy link
Author

bersace commented Dec 30, 2015

Pour toi @jpic 😍

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