Skip to content

Instantly share code, notes, and snippets.

@zyluo
Last active December 7, 2018 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zyluo/211dcd80837b45fdc674df835b2ba327 to your computer and use it in GitHub Desktop.
Save zyluo/211dcd80837b45fdc674df835b2ba327 to your computer and use it in GitHub Desktop.
Embedding python in bash script example
#/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