If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Friday, April 09, 2010

Sourcing a shell script

Sometime you want to emulate the action of "source" in bash, settings some environment variables.
Here's one way to do it:

from subprocess import Popen, PIPE
from os import environ

def source(script, update=1):
    pipe = Popen(". %s; env" % script, stdout=PIPE, shell=True)
    data = pipe.communicate()[0]

    env = dict((line.split("=", 1) for line in data.splitlines()))
    if update:
        environ.update(env)

    return env

2 comments:

Dotan Dimet said...

What about '.' ?
As in . foo.sh ?
isn't that the bash equivalent of source?

Miki Tebeka said...

. is used by bash in the same process. However when you use Popen you get a new environment and sometimes you want to populate it with some variables from a shell script - this is what this function does.

Blog Archive