tags:

views:

454

answers:

3

I'd like to embed the text of short python scripts inside of a bash script, for use in say, my .bash_profile. 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 -c option, and tell the interpreter to exec whatever it reads from stdin. 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 sys.stdin.read()')"
}

function traildirs() {
    pyexec <<END
trail=int('${1:-3}')
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
END
}

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.

+1  A: 

Why should you need to use -c? This works for me:

python << END
... code ...
END

without needing anything extra.

Heim
+3  A: 

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.

Ned Deily
Huh -- I had done a text search on the python man page, and the text `stdin` isn't in there. Looking more closely though, "standard input" is. Doh.
Matt Anderson
A: 

Interesting... I want an answer now too ;-)

He is not asking how to execute python code within a bash script but actually have the python set environment variables.

Put this in a bash script and try to get it to say "it worked".

export ASDF="it didn't work"

python <<END
import os
os.environ['ASDF'] = 'it worked'
END

echo $ASDF

The problem is that the python gets executed in a copy of the environment. Any changes to that environment aren't seen after python exits.

If there is a solution for this, I'd love to see it too.

eric.frederich
That isn't really what I was getting at necessarily, and I'm pretty sure you can't get environment variables from a child process (directly) or alter a parent's environment variables (directly). You *can* however `eval` the output of the python script in the bash script, thus executing arbitrary statements, setting environment variables or doing anything else you might like.
Matt Anderson
@Eric: If you really want an answer, post your own question.
Ned Deily
Matt, sorry... I briefly looked at your python script and saw you were doing stuff with os.environ and assumed that was the kind of thing you were doing.My mistake.
eric.frederich