Matt Anderson Matt Anderson - 2 months ago 7x
Python Question

embedding short python scripts inside a bash script

I'd like to embed the text of short python scripts inside of a bash script, for use in say, my

. What's the best way to go about doing such a thing?

The solution I have so far is to call the python interpreter with the
option, and tell the interpreter to
whatever it reads from
. From there, I can build simple tools like the following, allowing me to process text for use in my interactive prompt:

function pyexec() {
echo "$(/usr/bin/python -c 'import sys; exec')"

function traildirs() {
pyexec <<END
import os
home = os.path.abspath(os.environ['HOME'])
cwd = os.environ['PWD']
if cwd.startswith(home):
cwd = cwd.replace(home, '~', 1)
parts = cwd.split('/')
joined = os.path.join(*parts[-trail:])
if len(parts) <= trail and not joined.startswith('~'):
joined = '/'+joined
print joined

export PS1="\h [\$(traildirs 2)] % "

This approach smells slightly funny to me though, and I'm wondering what alternatives to doing it this way might be.

My bash scripting skills are pretty rudimentary, so I'm particularly interested to hear if I'm doing something silly from the bash interpreter's perspective.


The python interpreter accepts - on the command line as a synonym for stdin so you can replace the calls to pyexec with:

python - <<END

See command line reference here.