Last active
December 7, 2018 21:15
-
-
Save zyluo/211dcd80837b45fdc674df835b2ba327 to your computer and use it in GitHub Desktop.
Embedding python in bash script example
This file contains 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
#/usr/bin/which sh | |
set -e | |
PRE_SOURCEFILE=$(mktemp) | |
$(which python) - "${0}" "${@}" "--source" "${PRE_SOURCEFILE}" "--prefix" "PRE" <<END | |
import argparse | |
import sys | |
import tempfile | |
sys.argv = sys.argv[1:] | |
common = argparse.ArgumentParser(add_help=False) | |
common.add_argument('--source', help=argparse.SUPPRESS) | |
common.add_argument('--prefix', help=argparse.SUPPRESS) | |
parser = argparse.ArgumentParser(description='BLAH BLAH BLAH ' | |
'BLAH BLAH BLAH') | |
subparsers = parser.add_subparsers(title='BLAH BLAH BLAH ' | |
'BLAH BLAH BLAH', | |
dest='command', metavar='') | |
load = subparsers.add_parser('mod', parents=[common], | |
help='BLAH BLAH BLAH') | |
load.add_argument('dividend', type=int, help='dividend') | |
load.add_argument('divisor', type=int, help='divisor') | |
args = parser.parse_args() | |
with open(args.source, 'w') as f: | |
for arg in vars(args): | |
if arg in ['source', 'prefix']: | |
continue | |
val = getattr(args, arg) | |
if isinstance(val, list): | |
val = ','.join(val) | |
f.write('%s_%s="%s"\n' % (args.prefix, arg.upper(), val)) | |
END | |
if [[ -s ${PRE_SOURCEFILE} ]] | |
then | |
source ${PRE_SOURCEFILE} | |
else | |
exit 0 | |
fi | |
echo $((${PRE_DIVIDEND}%${PRE_DIVISOR})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment