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:

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

    ReplyDelete
  2. . 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.

    ReplyDelete